home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Collection of Tools & Utilities
/
Collection of Tools and Utilities.iso
/
c
/
jpl_c.zip
/
USEGUIDE.SI
< prev
next >
Wrap
Text File
|
1988-08-06
|
171KB
|
4,138 lines
.cw10
.po17
.pn 1
.PN 1
.FO 1-#
1. I N T R O D U C T I O N
The purpose of this manual is to describe the use and
installation of the Portable C Subroutine Library. This library
is a collection of modules written in the C language (Reference
[2]), that is capable of equivalent operation in multiple
environments. The library is available in source form for
compilation and integration into a system library to replace the
host vendor C library. Listings of the portable C library are
contained in a separate document (Reference [15]).
The content of the library consists of functions which minimize
the visibility of system-specific I/O formats, the use of system
commands, and the reliance on specific system resources. Some
customization is necessary, however, to accommodate the
ideosyncracies of each new host. Some of these ideosyncracies can
be removed by proper definition of parameters in header files
included when the portable library is recompiled. Others may
require a small amount of code alteration. A later section of
this document contains information and procedures for adapting
the portable C library in such cases.
The system I/O interface is restricted to the functions sbrk,
close, creat, exit, lseek, open, read, unlink, and write,
supplied by the host C language vendor. These are assumed to be
compatible with UNIXtm conventions. Another function , rename,
is assumed, either added by the C language vendor or by the
installer of this library. The floating point arithmetic system
interface consists of only a few functions, such as chrstc, fint,
ldexp, astof, and ftoa, that require some alteration of the
source code. The remainder of the library utilizes the standard
Kernighan and Ritchie (Reference [2]) C language features.
As many of the UNIX library functions as were deemed portable
were included in the portable C library. These bear the same
names here as they do in the parent library. Other functions
have been added for greater utility.
Descriptions in this manual follow the UNIX Programmer's Manual
format; in fact, the descriptions of the common functions were
adapted from the parent manual. The text is collected into a set
of subsections, which appear when applicable:
The heading of each entry gives a very short description of
the purpose of the functions in that entry.
The name subsection lists the exact names of the header or
subroutines covered under the entry.
*UNIX is a Trademark of Bell Laboratories.
The synopsis summarizes the use of the function being
described, including required include statements, formats,
and passed parameters. A few conventions are used:
Boldface words are considered literals, and are typed
just as they appear.
Square brackets [ ] around an argument indicate that
the argument is optional. When an argument is given as
'name', it always refers to a file name.
Ellipses '...' are used to show that the previous
argument-prototype may be repeated.
A final convention is used by the commands themselves.
An argument beginning with a minus sign '-' is often
taken to mean some sort of option-specifying argument
even if it appears in a position where a file name
could appear. Therefore, it is unwise to have files
whose names begin with '-'.
The description subsection discusses in detail the subject
at hand.
A see also subsection gives pointers to related information.
A diagnostics subsection discusses the diagnostic
indications which may be produced. Messages which are
intended to be self-explanatory are not listed.
The bugs subsection gives known bugs and sometimes
deficiencies. Occasionally the suggested fix is also
described.
.pa o
.PN 1
.FO 2-#
2. H E A D E R L I B R A R Y
This chapter describes each of the portable library standard
header files, which contain definitions of constants and macros
to be used when compiling user programs, and also when
recompiling the portable library itself. In addition, global.h
and stdio.h define global data structures; global.h is required
for each main segment, and stdio.h is required for all programs
which use buffered i/o.
Generally, all macros and constants defined in header files are
captalized, so that the user may know that they are such. The
exceptions are the global variables errno and progname, and
definitions of stdin, stdout, stderr, tiny, and utiny.
Generally, all system-dependent constants or switches are
contained in these header files. Thus customization for a new
system primarily involves changing only the header files
(stdio.h, mathcons.h). However some subroutines may also require
modification. See the customization notes for further
information concerning this subject.
The portable library standard header files are:
.uj0
ctype.h standard character-type macros
defs.h standard definitions and selectors file
errno.h standard error number definition file
global.h standard global variable header file
mathcons.h constant file for math functions
mathtyp.h header file to declare math functions
scrnio.h terminal display data file
stdio.h standard buffered i/o definition package
stdtyp.h standard defined-types file
.uj1
.pa
.hectype.h ctype.h
Standard Character-Type Macros
NAME
ctype.h
SYNOPSIS
#include <ctype.h>
BOOL ISALPHA(c)
int c;
. . .
DESCRIPTION
These macros classify ASCII-coded integer values by table
lookup. Each is a predicate returning nonzero for TRUE,
zero for FALSE. ISASCII is defined on all integer values;
the rest are defined only where ISASCII is TRUE and on the
single non-ASCII value EOF (see stdio.h). The conditions
for TRUE are:
.uj0
ISALNUM(c) c is an alphanumeric character.
ISALPHA(c) c is a letter.
ISASCII(c) c is an ASCII character, code less than 0x80.
ISCNTRL(c) c is a delete character (0x7f) or ordinary
control character (less than 0x20).
ISDIGIT(c) c is a digit.
ISLOWER(c) c is a lower case letter.
ISOCTAL(c) c is an octal character.
ISPRINT(c) c is a printing character, code 0x20
(space) through 0x7e (tilde).
ISPUNCT(c) c is a punctuation character (neither control
nor alphanumeric).
ISSPACE(c) c is a space, tab, carriage return, newline,
or formfeed.
ISUPPER(c) c is an upper case letter.
.uj1
The following use the ISUPPER and ISLOWER macros, and return
a character:
.uj0
TOLOWER(c) returns the lower case of c, or c if it is
lower case.
TOUPPER(c) returns upper case of c.
.uj1
SEE ALSO
corresponding list of functions.
BUGS
Because these are implemented as macros, side effects may
not be handled correctly; e.g. ISALPHA(*s++) may not
produce the intended result. Use the function form of these
macros in such cases.
.pa
.hedefs.h defs.h
Standard Definitions and Selectors File
NAME
defs.h
SYNOPSIS
#include <defs.h>
MAX(a, b)
...
DESCRIPTION
The following operators are defined in defs.h:
.uj0
AND replacement for '&&', the logical 'and'
operator.
FOREVER same as 'for (;;)', causes an infinite loop.
IS replaces '==', the logical equivalence
operator.
ISNT acts as the non-equivalence operator, '!='.
NOT substitute for '!', the logical negation
operator.
OR replaces '||', the logical inclusive-or
operator.
The standard constants defined in defs.h are the following:
EOF (-1)
FAIL 1
FALSE 0
NO 0
NULL 0
SUCCESS 0
TRUE 1
YES 1
Also in defs.h are several macros:
ABS(x) returns the absolute value of x.
GZ(x) returns x if x is greater than zero. If not,
it returns zero.
LURSHIFT(n, b) returns the value of long n after an unsigned
right shift of b bits.
MAX(x, y) returns the larger of x and y.
MIN(x, y) returns the lesser of x and y.
SGN(x) returns +1 if x is positive, -1 if negative,
or 0 if 0.
URSHIFT(n, b) returns the value of int n bits after an
unsigned right shift of b bits.
Examples:
if (statement1 AND statement2) ...
x = GZ(x);
FOREVER ...
if (op1 IS op2) ...
if (op1 ISNT op2) ...
while (NOT x) ...
while (statement1 OR statement2) ...
large = MAX(x, y);
.uj1
SEE ALSO
list of corresponding functions.
BUGS
Because ABS, GZ, MAX, MIN, SGN are implemented as macros,
side effects may not be handled properly. For example,
ABS(i++) may be incorrect. Use the function forms of these
macros in such cases.
.pa
.heerrno.h errno.h
Standard Error Number Definition File
NAME
errno.h
SYNOPSIS
#include <errno.h>
DESCRIPTION
errno.h defines error number values. The only two used in
the portable math library are:
.uj0
ERANGE computed math value is out of computable range.
EDOM function argument is not in defined domain.
.uj1
Other values of errno may be returned by system calls and
buffered i/o functions. Typical errno values returned by the
system calls used by the portable library are:
.uj0
ENOENT file does not exist
E2BIG argument list too long
EBADF bad file descriptor
ENOMEM not enough memory for requested operation
EEXIST file already exists on create request
EINVAL invalid argument
ENFILE exceeded maximum number of disk files
EMFILE exceeded maximum number of file descriptors
ENOTTY not a terminal or device to which calls apply
EACCES invalid access request
EIO i/o error during read or write
ENXIO no such device or address
EPERM modification forbidden except to owner, superuser
EFAULT bad address
EXDEV cross-device link attempted
ENODEV no such device
EFBIG file too large
ENOSPC no space left on device
EROFS read-only file system
EMLINK too many links to a file
.uj1
SEE ALSO
global.h
.pa
.heglobal.h global.h
Standard Global Variable Header File
NAME
global.h
SYNOPSIS
#include <global.h>
main(argc, argv)
STRING *argv;
DESCRIPTION
This header declares a global variable errno and a global
variable string progname to be used in those cases when
argv[0] does not contain the program name. The programmer
may use this variable to record the name, as
strcpy(progname, "<program name>");
If arg[0] does contain the name of the invoked program, then
the same effect is obtained via
strcpy(progname, argv[0]);
This file also contains outrow[] and outcol[] which contain
the row and column values of all output channels, indexed by
unit number. For buffered i/o, these are given by
fp->_unit; for unbuffered i/o, the unit numbers are STDOUT,
STDERR, and file descriptors returned by open.
.pa
.hemathcons.h mathcons.h
Constant File for Math Functions
NAME
mathcons.h
SYNOPSIS
#include <mathcons.h>
DESCRIPTION
This header file contains the values of the following
machine-dependent constants:
.uj0
BIG10X 10^(2^(BIG10X-1)) < INFINITY
BIGX 16 * log2(INFINITY) - 1
DPRECISION (int) PRECISION
INFINITY machine infinity, 2(MAXEXP-1)
INFINLEG INFINITY / sqrt(2)
LEAST least double representable
LOGINFINITY largest log argument
LOGLEAST smallest log argument
MAXEXP largest characteristic
MAXEXPG MAXEXP - 3 guard bits
MINEXP smallest characteristic
MINEXPG MINEXP + 3 guard bits
PRECISION -log10 of WASHOUT
RTHLFINF sqrt(INFINITY / 2)
SMALLX 16 * log2(LEAST) + 1
SYMLEAST symmetric least (has inverse)
TANHXBIG (sig. bits + 2) * ln(2) / 2
WASHOUT 1.0 + (x < WASHOUT) = 1.0
.uj1
mathcons.h also contains the following machine-independent
constants:
.uj0
CBRTFOUR cube root of 4
CBRTTWO cube root of 2
FADEOUT Taylor series fadeout term
FOURTHLOG2 log(2)/4
HALFLOG2e log2(e)/2
INVPI 1 / pi
LOG2 log of 2 base e
LOG2e log of e base 2
LOGe1 log of 10 base e
LOG10e log of e base 10
LOG10two log of 2 base 10
MAXANGLE int(pi * 225)
PI pi
PIover2 pi / 2
PIover3 pi / 3
PIover4 pi / 4
PIover6 pi / 6
ROOTHALF square root of 1/2
ROOTTWO square root of 2
SQRT3 sqrt(3)
SQRT3m1 sqrt(3) - 1
TWOLOG2e 2 * log2(e)
TWOmSQRT3 2 - sqrt(3)
TWOoverPI 2 / pi
.uj1
.pa
.hemathtyp.h mathtyp.h
Header File to Declare Math Functions
NAME
mathtyp.h
SYNOPSIS
#include <mathtyp.h>
DESCRIPTION
This contains type declarations which define the types of
all double math functions in this library. Using this
header deletes the necessity to declare each math function
separately in user programs. Included are:
acos cotan fmin modf sgn
asin erf frexp ntail simpson
atan erfc hypot nprob sin
atan2 exp inverf pow sinh
atof fabs inverfc randexp sqrt
cbrt fint ldexp randnorm tan
ceil floor log random tanh
cos frac log10 ratfun
cosh fmax log2 round
.pa
.hescrnio.h scrnio.h
Screen Function Data File
NAME
scrnio.h
SYNOPSIS
#include <scrnio.h>
DESCRIPTION
scrnio.h is the data file which declares all global data
necessary for the use of these terminal display functions.
It contains the values of the following constants:
ALT_SCRN[7] alternate intensity on
BKCURSOR[9] cursor back
CB4R boolean: column before row?
CLEARSCREEN[9] clear screen and home cursor
COFFSET column value offset
DNCURSOR[9] cursor down
EREOLN[7] erase to end-of-line
EREOPG[9] erase to end of page
FWCURSOR[9] cursor forward
HEIGHT lines per screen
HOMER[9] home the cursor
LEADIN[9] cursor lead-in sequence
LINDELETE[7] delete line
LININSERT[9] insert line
NORM_SCRN[7] normal intensity on
RCSEPARATOR[5] row-column separator
RCENDER[5] lead-in termination
ROFFSET row value offset
SCRNINI[9] initialize terminal
SCRNUNI[9] un-initialize terminal
SCRNWRAP boolean: screen wrap-around?
TERMINAL[20] name of terminal
UPCURSOR[9] cursor up
USELAST boolean: use last screen character?
WIDTH columns per screen
XLT2ASCII boolean: translate to ASCII?
SEE ALSO
scrnio in Section 4.
.pa
.hestdio.h stdio.h
Standard Buffered Input/Output Definition Package
NAME
stdio.h
SYNOPSIS
#include <stdio.h>
FILE *stdin;
FILE *stdout;
FILE *stderr;
DESCRIPTION
In the user-level frameworking scheme, the functions getc
and putc handle characters in both buffered and unbuffered
modes. The higher level routines gets, fgets, scanf,
fscanf, fread, puts, fputs, printf, fprintf, fwrite all use
getc and putc; they can be freely intermixed.
A file with associated buffering is called a stream, and is
declared to be a pointer to a defined type FILE. fopen
creates certain descriptive data for a stream and returns a
pointer to designate the stream in all further transactions.
There are three normally open streams with constant pointers
declared in the include file and associated with the
standard open files:
stdin standard input file
stdout standard output file
stderr standard error file
STDIN, STDOUT and STDERR are the file descriptors that read
and write recognize as standard preopened files.
A constant 'pointer' NULL (0) designates no stream at all.
An integer constant EOF (-1) is returned upon end of file or
error by integer functions that deal with streams.
MAXSTREAM is the maximum number of input/output streams,
and IObuffs is the file stream table.
Any routine that uses the standard input/output package must
include the header file <stdio.h> of pertinent macro
definitions.
Buffered Input/Output Definitions:
BUFSIZ stream buffer size
CRINSUP defined when '\r' in input text must be
suppressed
CROUTADD defined when '\r' must accompany '\n' in
text output
CURPOS file position designator (lseek)
FILEND file end position designator (lseek)
MAXLINE maximum stdio input line width
ORIGIN beginning of file designator (lseek)
PMODE fopen() protection mode (for UNIX)
SYS_EOF system end-of-file character (if any)
TABSTOP stdout tabstop width
_RDONLY file open for read only
_RDWRIT file open for read/write access
_WRONLY file open for write only
File Stream _flags bit masks:
_ALLBUF bit set (1) when buffer is allocated
_BUSY bit set (1) when a FILE is open
_DIRTY bit set (1) when buffer is unflushed
_EOF bit set (1) if stream EOF is reached
_IOERR bit set (1) if i/o stream error
File Stream Data Structure Definition, FILE *fp:
BUFFER _bend points one char past last in buffer
BUFFER _bptr current pointer in stream buffer
BUFFER _buff address of stream buffer
unsigned _buflen length of buffer
char _bytbuf single byte for unbuffered streams
TBITS _flags open mode, error, eof, busy, etc.
utiny _unit file descriptor returned by open
Standard I/O Macros:
clearerr(fp) ((fp)->_flags &= ~(_IOERR|_EOF)
getchar() getca(stdin)
feof(fp) (((fp)->_flags &_EOF) != 0)
ferror(fp) (((fp)->_flags &_IOERR) != 0)
fileno(fp) ((fp)->_unit)
putchar(c) putca(c, stdout)
eputc(c) putca(c, stderr)
SEE ALSO
open, close, read, write
DIAGNOSTICS
The value EOF is returned uniformly to indicate that a FILE
pointer has not been initialized with fopen, input (output)
has been attempted on an output (input) stream, or a FILE
pointer designates corrupt or otherwise unintelligible FILE
data.
.pa
.hestdtyp.h stdtyp.h
Standard Defined-Types File
NAME
stdtyp.h
SYNOPSIS
#include <stdtyp.h>
DESCRIPTION
Several bugs in C programs of an earlier generation were
found by rigorously type-defining and consistency-checking
such interfaces as function arguments, function returned
values, and structure definitions. This semantic
readability argument is the only justification for the
defined-types LBITS, BITS, TBITS, METACHAR, BOOL, and TBOOL,
because the underlying types are not subject to any
portability problems for their restricted usage.
The case is different for the types tiny, and utiny.
Portability problems (both machine and compiler) are a main
reason for these distinctions. Different versions of the
compiler have introduced data types for unsigned char,
unsigned short, and even unsigned long. And different
machines may treat the type char as signed or unsigned. If
programs are written with these raw C types, they must be
edited by hand before porting to another compiler that does
not support a new type. However, if a set of defined-types
is consistently used, then the defined-type can be targeted
to the new type when it exists, and be targeted to an older
base type otherwise. For true portability, such defined-
types must be augmented with rvalue macros:
.uj0
TINY(n) produces a signed value from 8 or more
bits of n.
UTINY(n) produces an unsigned value from 8 bits
(or more) of n.
Pseudo Storage Classes:
FAST equivalent to register.
GLOBAL equivalent to extern.
LOCAL equivalent to static.
Type definitions:
tiny an 8 bit (or larger) signed integer.
utiny an 8 bit (or larger) unsigned integer
used for a quantity.
TBITS an 8 bit (or larger) used for bit
manipulation.
TBOOL an 8 bit (or larger) integer, but used
for boolean.
TEXT an 8 bit (or larger) item used only for
characters.
BOOL integer, but used for boolean.
LBITS long, but only for bit manipulation.
BITS a 16 bit (or larger) integer only for
bit manipulation.
METACHAR a 16 bit (or larger) augmented
character (may be -1).
VOID a function that returns no value.
STRING a string of TEXT, (char *).
BUFFER a character array used as a buffer,
(char *).
ALIGN Storage allocation word alignment data
structure.
HEADER Storage allocation header.
.uj1
Except for tiny, and utiny, defined-types are written in
upper case to emphasize their definition in a header file.
This particular header file has been adapted from the Plum-
Hall Standard (Reference 4). This file must be customized
to the intended compiler/machine environment, as described
in the reference and Section 5 of this manual.
.he
.pa o
(Intentionally left blank)
.PA
.PN 1
.FO 3-#
3. S Y S T E M C A L L S
This section describes all the entries into the system assumed by
the portable C library. Most of these calls have an error
return. An error condition is indicated by an otherwise
impossible returned value. Almost always this is -1; the
individual sections specify the details. An error number is also
made available in the external variable errno. errno is not
cleared on successful calls, so it should be tested only after an
error has occurred.
The system calls assumed are:
close read
creat rename
exit sbrk
lseek unlink
open write
Source code for these functions is not contained in the portable
library; these functions expected to be available in the C
language system interface supported by the vendor.
.pa
.heclose close
Close a File, Operating System Interface
NAME
close
SYNOPSIS
int close(fildes)
int fildes;
DESCRIPTION
A file desciptor is an integer used in subsequent
invocations of other input-output functions on the file.
Given a file descriptor such as returned from an open or
creat, close closes the associated file. A close of all
files is automatic on exit, but since there is a limit on
the number of open files per process, close is necessary for
programs which deal with many files.
SEE ALSO
open, write, creat, fclose
DIAGNOSTICS
close returns a zero if a file is closed; EOF is returned
for an unknown file descriptor.
.pa
.hecreat creat
Create a File, Operating System Interface
NAME
creat
SYNOPSIS
int creat(name, mode)
STRING name;
int mode;
DESCRIPTION
creat creates a new file or prepares to rewrite an existing
file called name, given as the address of a null-terminating
string. If the file did not exist, it is given the
prescribed mode.
If the file did exist, its mode and owner remain unchanged
but it is truncated to zero length.
The file is also opened for writing, and its file descriptor
is returned.
The mode given is arbitrary; it need not allow writing.
This feature is system-dependent, originally used by
programs which deal with temporary files of fixed names.
The creation was done as a mode that forbids writing. Then
if a second instance of the program were to attempt a creat,
an error is returned and the program knows that the name is
unusable for the moment. However, this feature is not
guaranteed in the portable library, and should not be relied
upon.
SEE ALSO
open, write, close, stdio.h
DIAGNOSTICS
For creat, the value EOF is returned if: a needed directory
is not searchable; the file does not exist and the directory
in which it is to be created is not writable; the file does
exist and is unwritable; the file is a directory; there are
already too many files open.
.pa
.heexit exit
Terminate Process
NAME
exit, _exit
SYNOPSIS
VOID exit(status)
int status;
VOID _exit(status)
int status;
DESCRIPTION
exit is the normal means of terminating a process. exit is
supposed to close all the process's files; however, it may
not close buffered streams of the portable library. For
this purpose, the portable function fclose is available.
status may be available to whatever process called this one,
depending on the system, so the success or failure of the
program can be tested by another program that uses this one
as a sub-process.
This call can never return.
The C function exit may cause cleanup actions before the
final 'sys exit'. The function _exit circumvents all
cleanup.
SEE ALSO
fclose, redirbuf
.pa
.helseek lseek
Move Read/Write Pointer
NAME
lseek
SYNOPSIS
long lseek(fildes, offset, whence)
int fildes;
long offset;
int whence;
DESCRIPTION
The file descriptor refers to a file open for reading or
writing. The read (resp. write) pointer for the file is set
as follows:
If whence is ORIGIN (0), the pointer is set to offset
bytes.
If whence is CURPOS (1), the pointer is set to its
current location plus offset.
If whence is FILEND (2), the pointer is set to the
size of the file plus offset.
The returned value is the resulting pointer location.
Seeking far beyond the end of a file, then writing, creates
a gap or hole, which occupies no physical space and reads as
zeros.
SEE ALSO
open, creat, fseek, stdio.h
DIAGNOSTICS
EOF is returned for an undefined file descriptor, or seek to
a position before the beginning of file.
.pa
.heopen open
Open for Reading or Writing
NAME
open
SYNOPSIS
int open(name, flag, mode)
STRING name;
int flag, mode;
DESCRIPTION
open opens the file name for reading (if flag is _RDONLY,
0), writing (if flag is _WRONLY, 1) or for both reading and
writing (if flag is _RDWRIT, 2). name is the address of a
string of ASCII characters representing the filename,
terminated by a NULL character.
The file is positioned at the beginning (byte 0). The
returned file descriptor must be used for subsequent calls
for other input-output functions on the file.
The mode is arbitrary, and is unused for the flag values of
the portable library. The presence or absence of the mode
argument may require modules calling the open function to be
modified to conform with the requirements of the host
computer.
SEE ALSO
creat, read, write, close, fopen, stdio.h
DIAGNOSTICS
The value EOF is returned if the file does not exist, if one
of the necessary directories does not exist or is
unreadable, if the file is not readable (resp. writable), or
if too many files are open.
.pa
.heread read
Read from File
NAME
read
SYNOPSIS
int read(fildes, buffer, nbytes)
int fildes, nbytes;
BUFFER buffer;
DESCRIPTION
A file descriptor is the int value returned from a
successful open or creat. buffer is the location of nbytes
contiguous bytes into which the input will be placed. It is
not guaranteed that all nbytes bytes will be read; for
example, if the file refers to a typewriter at most one line
will be returned. In any event, the number of characters
read is returned.
If the returned value is zero, then end-of-file has been
reached.
SEE ALSO
open, creat
DIAGNOSTICS
As mentioned, NULL (0) is returned when the end of the file
has been reached. If the read was otherwise unsuccessful
the return value is EOF. Many conditions can generate an
error: physical I/O errors, bad buffer address, preposterous
nbytes, file descriptor not that of an input file.
BUGS
Some systems may contain internal buffering to make use of
terminal line editing features of some operating systems.
Therefore, read(0, buffer, 1) may not respond properly for
character-by-character inputs.
.pa
.herename rename
Rename a File
NAME
rename
SYNOPSIS
int rename(old, new)
STRING old, new;
DESCRIPTION
rename changes the name of a file from old to new.
DIAGNOSTICS
rename returns the value NULL if successful, and EOF is not.
.pa
.hesbrk sbrk
Change Core Allocation
NAME
sbrk
SYNOPSIS
STRING sbrk(incr)
int incr;
DESCRIPTION
In sbrk, incr more bytes are added to the program's data
space and a pointer to the start of the lowest location not
used by program (called the break) is returned.
SEE ALSO
malloc, free
DIAGNOSTICS
An EOF (-1) is returned if the program requests more memory
than the system limit or if other operating system internal
contraints are violated.
BUGS
Setting the break in the range 0177701 to 0177777 (on the
PDP11) is the same as setting it to zero.
.pa
.heunlink unlink
Remove Directory Entry
NAME
unlink
SYNOPSIS
int unlink(name)
STRING name;
DESCRIPTION
name points to a null-terminated string. unlink removes the
entry for the file identified by name from its directory.
If this entry was the last link to the file, the contents of
the file are freed and the file is destroyed. If, however,
the file was open in any process, the actual destruction is
delayed until it is closed, even though the directory entry
has disappeared.
DIAGNOSTICS
NULL (0) is normally returned; EOF indicates that the file
does not exist, that its directory cannot be written, or
that the file contains pure procedure text that is currently
in use. Write permission is not required on the file
itself. It is also illegal to unlink a directory (except
for the super-user, in UNIX).
.pa
.hewrite write
Write on a File
NAME
write
SYNOPSIS
int write(fildes, buffer, nbytes)
int fildes, nbytes;
BUFFER buffer;
DESCRIPTION
A file descriptor is an integer returned from a successful
open or creat.
buffer is the address of nbytes contiguous bytes, which are
written on the output file. The number of characters
actually written is returned. It should be regarded as an
error if the returned value is not the same as nbytes.
Writes of a certain size may be more efficient on some
machines, depending on implementation particulars.
SEE ALSO
creat, open
DIAGNOSTICS
Returns EOF on error: bad descriptor, buffer address, or
count; physical I/O errors.
.he
.pa o
(Intentionally left blank)
.PA
.PN 1
.FO 4-#
4. F U N C T I O N L I B R A R Y
This chapter describes functions contained in the portable C
function library.
Functions in the math library may return conventional values when
the function is undefined for the given arguments or when the
value is not representable. In these cases the external variable
errno is set to the value EDOM or ERANGE. The values of EDOM and
ERANGE are defined in the include file <errno.h>.
Many entries contain more than one function; however, all
function names (and short definition, if different from name) are
included in the index for easy access.
Because of file space limitations in some host systems, the
conglomeration of functions into files is expected to be host-
dependent; and, therefore, not covered here. A list of source
files and the functions they contain is given in Section 5.
.pa
.heabs abs
Absolute Values
NAME
abs, fabs, labs
SYNOPSIS
int abs(i)
int i;
double fabs(x)
double x;
long labs(n)
long n;
DESCRIPTION
abs is a function returning the absolute value of its
integer operand.
ABS is the macro in header file defs.h, which performs the
same operation as the function abs, but may have side
effects. ABS works for all numeric types.
fabs returns the absolute value |x|.
labs returns the long integer absolute value of its long
operand, n.
BUGS
You get what the hardware gives on the largest negative
integer.
.pa
allot allot
Memory Allocation Package
NAME
allot, liberate
SYNOPSIS
STRING allot(nbytes)
unsigned nbytes;
VOID liberate(ptr, nbytes)
STRING ptr;
unsigned nbytes;
DESCRIPTION
allot and liberate provide a simple, general-purpose memory
allocation package. allot returns a pointer to a block of
at least nbytes bytes. The arguments of liberate define a
block to be made available for further allocation. The
liberated block need not have been previously allotted.
Needless to say, grave disorder will result if the space
assigned by allot is overrun or if some random ptr or
oversize nbytes is handed to liberate.
allot allocates the first big-enough contiguous reach of
free space found in a circular search from the last block
allocated or freed, coalescing adjacent free blocks as it
searches. It calls sbrk to get more memory from the system
when there is no suitable space already free.
allot and liberate work much the same as malloc and free.
The differences are that malloc and free operate with blocks
that contain an overhead structure, and freed blocks must
have been previously allocated, whereas allotted blocks
contain no such overhead, and liberated blocks may be freely
added to the available store. Blocks are allotted and
liberated in units of size sizeof(HEADER) bytes.
DIAGNOSTICS
allot returns a NULL pointer (0) if there is no available
memory or if the operating system has detected corruption
outside the allotted area.
SEE ALSO
malloc, free
.pa
.heatof atof
ASCII/Numeric Conversion
NAME
astof, astoi, astol, atof, atoi, atol, ftoa, itoa, itoab,
ltoa, ltoab, tobase, utoa
SYNOPSIS
STRING astof(s, val)
STRING s;
double *val;
STRING astoi(s, val)
STRING s;
int *val;
STRING astol(s, val)
STRING s;
long *val;
double atof(s)
STRING s;
int atoi(s)
STRING s;
long atol(s)
STRING s;
STRING ftoa(s, x, pr, mode)
STRING s;
double x;
int pr;
char mode;
STRING itoa(s, n, w)
STRING s;
int n, w;
STRING itoab(s, n, w, b)
STRING s;
int n, w, b;
STRING ltoa(s, n, w)
STRING s;
long n;
int w;
STRING ltoab(s, n, w, b)
STRING s;
long n;
int w, b;
METACHAR tobase(ch, base)
char ch;
int base;
STRING utoa(s, n, w)
STRING s;
unsigned n;
int w;
DESCRIPTION
astof, astoi and astol convert a string pointed to by s to
floating, integer, and long integer val representation
respectively. The first unrecognized character ends the
string. They operate in the same way as atof, atoi and
atol, except that they store the value in val, and return a
pointer to the next unused character.
atof, atoi, and atol functions convert a string pointed to
by s to floating, integer, and long integer representation,
respectively. The first unrecognized character ends the
conversion.
atof recognizes an optional string of tabs and spaces, then
an optional sign, then a string of digits optionally
containing a decimal point, then an optional 'e' or 'E'
followed by an optionally signed integer.
atoi and atol recognize an optional string of tabs and
spaces, then an optional sign, then a string of digits. If
the string begins in '0x', then the number is assumed to be
hexadecimal; otherwise, if the leading digit is '0', the
string is interpreted as an octal.
ftoa converts x to an ASCII string s with precision pr in
mode 'e', 'f', or 'g' format. This function returns the
pointer to s. The mode argument may also be 0, 1 or 2 to
designate 'e', 'f', or 'g', respectively.
itoa converts an integer to ASCII. It returns a pointer to
s, which contains the ASCII value of n to minimum width |w|,
0-filled if w<0, else space-filled. This function is a
modified version of itoa() found in Kernighan and Ritchie
(see Reference 2, pp. 60), with modifications as suggested
in exercises 3-3 and 3-5, and with returned pointer to
result string.
itoab converts an integer n to a minimum of |w| ascii
characters, base b. It returns a pointer to s, which
contains the ASCII value. If w is less than zero, s is
zero-filled; otherwise, it is space-filled.
ltoa converts a long n to a minimum of |w| ASCII characters
(0-filled if w < 0, and space-filled otherwise), and puts
them in s, returning the pointer to s. This is also a
modified version of itoa() from Kernigan and Ritchie, with
modifications as suggested in exercises 3-3 and 3-5, for use
with the long data type. (see Reference 2, pp. 60)
ltoab converts long n to a minimum of w ascii characters,
base b, and puts the ASCII in s, returning a pointer to s.
tobase returns the value of character ch to base base, if
valid, or EOF if not.
utoa returns a pointer to the string s, which contains ASCII
value of unsigned n, base 10, with minimum width |w| (0-
filled if w < 0, and space-filled otherwise). This function
is another modified version of itoa() found in K & R (see
Reference 2, pp. 60), with modifications as suggested in
exercises 3-4 and 3-5, and with returned pointer to result
string.
SEE ALSO
scanf
BUGS
There are no provisions for overflow.
.pa
.hebitcount bitcount
Count Bits in Argument
NAME
bitcount
SYNOPSIS
int bitcount(i)
BITS i;
DESCRIPTION
bitcount is a K & R function (Reference 2, page 47) which
counts and returns the number of 1-bits in i.
.pa
.heclearerr clearerr
Stream Status Inquiries
NAME
clearerr, feof, ferror, fileno
SYNOPSIS
#include <stdio.h>
VOID clearerr(stream)
FILE *stream;
BOOL feof(stream)
FILE *stream;
BOOL ferror(stream)
FILE *stream;
int fileno(stream)
FILE *stream;
DESCRIPTION
clearerr resets (sets to 0) the error indication on the
named stream.
feof returns non-NULL when end of file is read on the named
input stream, otherwise it returns NULL.
ferror returns non-NULL if an error has occurred on FILE
stream; otherwise, it returns NULL.
fileno returns the integer file descriptor associated with
the stream; see open.
In UNIX, these functions are implemented as macros; they
cannot be redeclared. Here, however, they are normal
functions and do not have the possible side effects of
macros.
They do have corresponding macros, found in stdio.h:
CLEARERR, FEOF, FERROR, and FILENO.
SEE ALSO
fopen, open
.pa
.heerf erf
Gaussian Error Functions and Inverses
NAME
erf, erfc, inverf, inverfc
SYNOPSIS
double erf(x)
double x;
double erfc(x)
double x;
double inverf(x)
double x;
double inverfc(x)
double x;
DESCRIPTION
erf returns the error function of x, as defined in Handbook
of Mathematical Functions (See Reference 3, pp. 297).
erfc returns the complimentary error function of x,
1-erf(x).
Coefficients for the above functions are from Schonfelder
(see Reference 7).
inverf returns the inverse of the error function, erf. This
routine uses the approximations given in "Rational Chebyshev
Approximations for the Inverse Error Function", (see
Reference 8, pp. 827-830)
inverfc returns the inverse of the complementary error
function, erfc.
DIAGNOSTICS
In inverf, if |x| > 1.0, errno is set to EDOM. In inverfc,
if |x| < 0 or > 2, errno is set to EDOM, and if x is zero,
it is set to ERANGE. In each of these cases, INFINITY or
-INFINITY is returned for positive or negative x,
respectively;
.pa
.heexp exp
Mathematical Functions
NAME
exp, log, log10, log2, pow, sqrt, cbrt
SYNOPSIS
double exp(x)
double x;
double log(x)
double x;
double log10(x)
double x;
double log2(x)
double x;
double pow(x,y)
double x, y;
double sqrt(x)
double x;
double cbrt(x)
double x;
DESCRIPTION
All functions above except cbrt were programmed using the
algorithms in Coty and Waite (Reference 5).
exp returns the exponential function of x, ex, (see
Reference 5, pp. 60-83).
log returns the natural logarithm of x (see Reference 5, pp.
35-59).
log10 returns the common (base 10) logarithm, and log2
returns the binary logarithm (base 2) of x.
pow returns x raised to the power of y, where x > 0, xy (see
Reference 5, pp. 84-124).
sqrt returns the square root of x, for x > 0 (see Reference 5,
pp. 17-34).
cbrt returns the cube root of x (see Reference 6).
SEE ALSO
hypot, sinh
DIAGNOSTICS
exp and pow return INFINITY when the correct value would
overflow; errno is set to ERANGE. pow returns zero and
sets errno to EDOM when the second argument is negative and
non-integral, and also when both arguments are zero.
log returns zero when x is zero or negative; errno is set
to EDOM.
sqrt returns zero when x is negative; errno is set to EDOM.
.pa
.hefclose fclose
Close or Flush a Stream
NAME
fclose, fflush, flush
SYNOPSIS
#include <stdio.h>
int fclose(stream)
FILE *stream;
int fflush(stream)
FILE *stream;
int flush(stream, c)
FILE *stream;
int c;
DESCRIPTION
fclose causes any buffers for the named stream to be
emptied, and the file to be closed. Buffers allocated by
the standard input/output system are freed.
fclose is performed automatically upon calling exit, on all
open files.
fflush causes any buffered data for the named output stream
to be written to that file. The stream remains open.
flush writes any buffered characters onto FILE stream; then
if c isn't EOF, it puts it in the buffer.
SEE ALSO
close, fopen
DIAGNOSTICS
These routines return EOF if stream is not associated with
an output file, or if buffered data cannot be transferred to
that file. NULL is returned on success.
.pa
.hefint fint
Absolute Value, Rounding, Integer and Fractional Part Functions
NAME
fint, frac, chrstc, floor, ceil, round
SYNOPSIS
double fint(x)
double x;
double frac(x)
double x;
int chrstc(x)
double x;
double floor(x)
double x;
double ceil(x)
double x;
double round(x)
double x;
DESCRIPTION
fint returns the integer part of x as a double.
frac returns the fractional part of x, i.e. x - fint(x).
chrstc returns the characteristic (2's exponent) of double
x. The mantissa is in [.5,1).
floor returns the largest integer not greater than x.
ceil returns the smallest integer not less than x.
round returns x rounded to the nearest integer in magnitude.
.pa
.hefopen fopen
Open a Stream
NAME
fopen
SYNOPSIS
#include <stdio.h>
FILE *fopen(filename, type)
STRING filename, type;
DESCRIPTION
fopen opens the file named by filename and associates a
stream with it. fopen returns a pointer to be used to
identify the stream in subsequent operations.
type is a character string having one of the following
values:
"r" open for reading
"w" create for writing
"a" append: open for writing at end of file, or create for
writing
"r+" open for reading and writing. same a "r" but the
device or file may also be written to.
"w+" open for reading and writing. same as "w" but the
device or file may also be read.
"a+" open for append and read. same as "a" but the device
or file may also be read.
SEE ALSO
open, fclose
DIAGNOSTICS
fopen returns the pointer NULL if filename cannot be
accessed.
.pa
.hefread fread
Buffered Input/Output
NAME
fread, fwrite
SYNOPSIS
#include <stdio.h>
int fread(ptr, ptrsize, nitems, stream)
BUFFER ptr;
int ptrsize, nitems;
FILE *stream;
int fwrite(ptr, ptrsize, nitems, stream)
BUFFER ptr;
int ptrsize, nitems;
FILE *stream;
DESCRIPTION
fread reads, into a block beginning at ptr, nitems items of
ptrsize bytes from the named input stream. It returns the
number of items actually read.
fwrite appends at most nitems items of ptrsize bytes of type
*ptr to the FILE stream. It returns the number of items
actually written.
SEE ALSO
read, write, fopen, getc, putc, gets, puts, printf, scanf
DIAGNOSTICS
fread and fwrite return NULL upon end of file or error.
.pa
.hefrexp frexp
Mantissa and Exponent Functions
NAME
frexp, ldexp, modf
SYNOPSIS
double frexp(value, eptr)
double value;
int *eptr;
double ldexp(value, exp)
double value;
int exp;
double modf(value, iptr)
double value, *iptr;
DESCRIPTION
frexp returns the mantissa of a double value as a double
quantity, x, of magnitude in the interval [0.5, 1), and
stores an integer n such that value = x * 2n indirectly
through eptr.
ldexp returns the quantity value*2exp.
modf returns the fractional part of value, i.e.,
frac(value), and stores the integer part indirectly through
iptr, i.e., *iptr = fint(value).
BUGS
The definition of modf appears to be somewhat different than
that given in Ref. 1 for negative value arguments.
SEE ALSO
frac, fint
.pa
.hefseek fseek
Reposition a Stream
NAME
fseek, ftell, rewind
SYNOPSIS
#include <stdio.h>
int fseek(stream, offset, whence)
FILE *stream;
long offset;
int whence;
long ftell(stream)
FILE *stream;
int rewind(stream)
FILE *stream;
DESCRIPTION
fseek sets the position of the next input or output
operation on the stream. The new position is at the signed
distance offset bytes from the beginning, the current
position, or the end of the file, according as whence has
the value ORIGIN (0), CURPOS (1), or FILEND (2).
fseek undoes any effects of ungetc.
ftell returns the current value of the offset in bytes
relative to the ORIGIN of the FILE stream, measured in
bytes.
On some systems, ftell may be the only foolproof way to
obtain an offset for fseek.
rewind(stream) is equivalent to fseek(stream, OL, ORIGIN).
It sets the FILE fp to the ORIGIN.
SEE ALSO
lseek, fopen
DIAGNOSTICS
fseek and rewind return EOF for improper seeks.
.pa
.hegetbuf getbuf
Get a Buffer
NAME
getbuf
SYNOPSIS
VOID getbuf(fp)
FAST FILE *fp;
DESCRIPTION
getbuf gets a buffer either from allot or else it uses the
bytbuf, attaching to the FILE fp.
.pa
.hegetc getc
Get Character or Word from Stream
NAME
getc, getca, getchar, getf, geti, getl
SYNOPSIS
#include <stdio.h>
int getc(stream)
FILE *stream;
int getca(stream)
FILE *stream;
int getchar()
double getf(prompt, check, low, high)
STRING prompt;
BOOL check;
double low, high;
int geti(prompt, check, low, high)
STRING prompt;
BOOL check;
int low, high;
long getl(prompt, check, low, high)
STRING prompt;
BOOL check;
long low, high;
DESCRIPTION
getc returns the next character from the named input stream.
getca is the same as getc, except that '\r' characters input
from the stream are suppressed (when compiled with the
CRINSUP switch in stdio.h TRUE).
getchar() is identical to getca(stdin). stdio.h contains
the macro, GETCHAR which is the same as this function.
getf prints prompt on stdout, then reads from stdin a
double, which it returns. If check is TRUE, doubles outside
of the low - high bounds will not be accepted.
geti and getl work the same as getf, except that they return
an integer and a long, respectively.
The standard input stream stdin is normally buffered if and
only if the input refers to a device other than a terminal.
When an input stream is unbuffered, information is returned
from getc as soon as it is written; when it is buffered,
many characters are saved up and returned by getc only after
a newline is encountered. To ensure portability of
programs, always use setbuf to set the proper buffering mode
at the beginning.
SEE ALSO
fopen, putc, gets, scanf, fread, ungetc, setbuf
DIAGNOSTICS
These functions return the integer constant EOF at end of
file or upon read error.
BUGS
Some systems may contain internal buffering to make use of
terminal line editing features of some operating systems,
even when unbuffered input is desired. Therefore getchar
may not respond properly for character-by-character inputs.
.pa
.hegets gets
Get a String from a Stream
NAME
gets, getns, fgets
SYNOPSIS
#include <stdio.h>
STRING gets(s)
STRING s;
STRING getns(p, s, n)
STRING p, s;
int n;
STRING fgets(s, n, stream)
STRING s;
FILE *stream;
int n;
DESCRIPTION
gets reads a text string into s from the standard input
stream stdin. The string input is terminated by a newline
character, which is replaced in s by a NULL character. gets
returns its argument.
getns prompts stdout with the string p, then reads n - 1
characters, or up to a newline character, whichever comes
first, from stdin. The last caracter read into s is
followed by NULL. getns returns s. Characters entered
after the (n - 1)th, up to and including a newline
character, are discarded.
fgets reads n-1 text characters, or up to a newline
character, whichever comes first, from the stream into the
string s. The last character read into s is followed by a
NULL character. fgets returns s.
SEE ALSO
puts, getc, scanf, fread
DIAGNOSTICS
gets and fgets return the constant pointer NULL upon end of
file, empty s or error.
BUGS
gets deletes a newline, fgets keeps it, all in the name of
backward compatibility.
.pa
.hehypot hypot
Euclidian Distance Function
NAME
hypot
SYNOPSIS
double hypot(x, y)
double x, y;
DESCRIPTION
hypot returns
sqrt(x*x + y*y),
taking precautions against unwarranted overflows.
SEE ALSO
sqrt
DIAGNOSTICS
The INFINITY value is returned on overflow, and errno is set
to ERANGE.
.pa
.heindex index
String Operation Functions
NAME
index, rindex, stradd, strcat, strncat, strcmp, strncmp,
strcpy, strncpy, streql, strindex, strlen, strsave
SYNOPSIS
STRING index(s, c)
STRING s;
char c;
STRING rindex(s, c)
STRING s;
char c;
STRING stradd(n, s, arg[, ...])
STRING s, arg, ...;
STRING strcat(s1, s2)
STRING s1, s2;
STRING strncat(s1, s2, n)
STRING s1, s2;
int n;
int strcmp(s1, s2)
STRING s1, s2;
int strncmp(s1, s2, n)
STRING s1, s2;
int n;
STRING strcpy(s1, s2)
STRING s1, s2;
STRING strncpy(s1, s2, n)
STRING s1, s2;
int n;
BOOL streql(s, t)
STRING s, t;
int strindex(s, t)
STRING s, t;
int strlen(s)
STRING s;
STRING strsave(s)
STRING s;
DESCRIPTION
These functions operate on null-terminated strings. They do
not check for overflow of any receiving string.
index (rindex) returns a pointer to the first (last)
occurance of character c in string s, or NULL if c does not
occur in the string.
strcat appends a copy of string s2 to the end of string s1.
strncat copies at most n characters. Both return a pointer
to the null-terminated result. stradd concatenates n
strings, s and arg[, ...].
strcmp compares its arguments and returns an integer greater
than, equal to, or less than zero, according as s1 is
lexicographically greater than, equal to, or less than s2.
strncmp makes the same comparison, but looks at at most n
characters.
strcpy copies string s2 to s1. strncpy copies n characters
of s2, or all of s2, whichever is less. Both return s1.
streql returns TRUE if strings s and t are the same.
strindex locates one string in another, returns the index of
t in s, or EOF if it does not exist. This is the index
function given in Kernighan and Ritchie, page 67 (see
Reference 2).
strlen returns the number of non-NULL characters in s.
strsave gets enough strorage for s and puts it there,
returns the pointer to the string, or NULL if there is
insufficient string space. This is from Kernighan and
Ritchie (see Reference 2, pp. 103).
.pa
.heisalpha isalpha
Character Classification Functions
NAME
isalnum, isalpha, isascii, iscntrl, isdigit, ishex, islower,
isoctal, isprint, ispunct, isspace, isupper
SYNOPSIS
BOOL isalpha(c)
int c;
. . .
DESCRIPTION
These functions classify ASCII-coded integer values by table
lookup. Each is a predicate returning nonzero for TRUE,
zero for FALSE. isascii is defined on all integer values;
the rest are defined only where isascii is TRUE and on the
single non-ASCII value EOF (see stdio). The conditions for
a return of TRUE are
.uj0
isalnum c is an alphanumeric character.
isalpha c is a letter.
isascii c is an ASCII character, code less than 0x80.
iscntrl c is a delete character (0x7f) or ordinary
control character (less than 0x20).
isdigit c is a digit.
ishex c is a hex number, 0 - 9, a - f.
islower c is a lower-case letter.
isoctal c is an octal digit, 0 - 7.
isprint c is a printing character, code 0x20
(space) through 0x7e (tilde).
ispunct c is a punctuation character (neither control
nor alphanumeric).
isspace c is a space, tab, carriage return, newline,
or formfeed.
isupper c is an upper-case letter.
.uj1
SEE ALSO
Macros corresponding to each of these functions are
available in ctype.h.
.pa
.heisok isok
Quesion User
NAME
isok
SYNOPSIS
BOOL isok(prompt)
STRING prompt;
DESCRIPTION
prompt outputs to stdout and accepts a y/n answer. It
returns TRUE for y, and FALSE for n.
.pa
.hemalloc malloc
Main Memory Allocator
NAME
malloc, free, realloc, calloc
SYNOPSIS
STRING malloc(nbytes)
unsigned nbytes;
VOID free(ptr)
STRING ptr;
STRING realloc(ptr,size)
STRING ptr;
unsigned size;
STRING calloc(nelem, elsize)
unsigned nelem, elsize;
DESCRIPTION
malloc and free provide a simple general-purpose memory
allocation package. malloc returns a pointer to a block of
at least nbytes bytes beginning on a word boundary.
The argument to free is a pointer to a block previously
allocated by malloc; this space is made available for
further allocation, but its contents are left undisturbed.
Needless to say, grave disorder will result if the space
assigned by malloc is overrun or if some random number is
handed to free.
malloc allocates the first big-enough contiguous reach of
free space found in a circular search from the last block
allocated or freed, coalescing adjacent free blocks as it
searches. It calls sbrk to get more memory from the system
when there is no suitable space already free.
realloc changes the size of the block pointed to by ptr to
size bytes and returns a pointer to the (possibly moved)
block. The contents will be unchanged up to the lesser of
the new and old sizes.
realloc also works if ptr points to a block freed since the
last call of malloc, realloc or calloc; thus, sequences of
free, malloc and realloc can exploit the search strategy of
malloc to do storage compaction.
calloc allocates space for an array of nelem elements of
size elsize. The space is initialized to zeros.
Each of the allocation routines returns a pointer to space
suitably aligned (after possible pointer coercion) for
storage of any type of object.
DIAGNOSTICS
malloc, realloc and calloc return a NULL pointer (0) if
there is no available memory or if the operating system has
detected storage corruption outside the allocated areas.
SEE ALSO
allot, liberate
BUGS
When realloc returns zero, the block pointed to by ptr may
be destroyed.
.pa
.hemax max
Maximum and Mimimum Function for Integers, Doubles and Longs
NAME
max, min, fmax, fmin, lmax, lmin
SYNOPSIS
int max(a, b)
int a, b;
int min(a, b)
int a, b;
double fmax(x, y);
double x, y;
double fmin(x, y);
double x, y;
long lmax(x, y)
long x, y;
long lmin(x, y)
long x, y;
DESCRIPTION
max and min find the maximum and the minimum of integers a
and b. fmax and fmin do the same for doubles; lmax and
lmin do the same for longs.
MAX and MIN are macros in defs.h which take the maximum and
minimum values of any numeric type.
SEE ALSO
defs.h
.pa
.henprob nprob
Normal Probability Functions
NAME
nprob, nprobc
SYNOPSIS
double nprob(x)
double x;
double nprobc(x)
double x;
DESCRIPTION
nprob is the normal cumulative probability function of a
random variable having unit variance and zero mean, i.e.
Pr{z <= x}.
nprobc is the complementary cumulative normal probability
function, i.e., nprobc(x) = 1 - nprob(x).
SEE ALSO
erf, erfc
.pa
.heprintf printf
Formatted Output Conversion
NAME
printf, fprintf, eprintf, sprintf, format
SYNOPSIS
#include <stdio.h>
VOID printf(fmt [, arg ] ... )
STRING fmt;
unsigned arg;
VOID fprintf(stream, fmt [, arg ] ... )
FILE *stream;
STRING fmt;
unsigned arg;
VOID eprintf(fmt [, arg ] ... )
STRING fmt;
unsigned arg;
VOID sprintf(s, fmt [, arg ] ... )
STRING s, fmt;
unsigned arg;
VOID format(putsub, fmt, args)
int (*putsub)();
STRING fmt;
unsigned args;
DESCRIPTION
printf places output on the standard output stream stdout.
fprintf places output on the named output stream.
eprintf(fmt [, arg ] ... ) places output on stderr. sprintf
places output in the string s, followed by the NULL
character. format places output using the putsub of a list
of items pointed to by args.
Each of these functions converts, formats, and prints its
arg arguments under control of the fmt argument. The fmt is
a character string which contains two types of objects:
plain characters, which are simply copied to the output
stream, and conversion specifications, each of which causes
conversion and printing of the next successive arg of the
list.
Each conversion specification is introduced by the character
%. Following the %, there may be
- an optional minus sign which specifies left
adjustment of the converted value in the indicated
field;
- an optional digit string specifying a field width; if
the converted value has fewer characters than the
field width it will be blank-padded on the left (or
right, if the left-adjustment indicator has been
given) to make up the field width; if the field width
begins with a zero, zero-padding will be done instead
of blank-padding;
- an optional period which serves to separate the field
width from the next digit string;
- an optional digit string specifying a precision which
specifies the number of digits to appear after the
decimal point, for e- and f-conversion, or the maximum
number of characters to be printed from a string;
- the character l specifying that a following d, o, x,
or u corresponds to a long integer arg. (A
capitalized conversion code accomplishes the same
thing.)
- a character which indicates the type of conversion to
be applied.
A field width or precision may be '*' instead of a digit
string. In this case an integer arg supplies the field
width or precision.
The conversion characters and their meanings are
d,o,x The integer arg is converted to decimal, octal, or
hexadecimal notation respectively.
f The float or double arg is converted to decimal
notation in the style '[-]ddd.ddd' where the number of
d's after the decimal point is equal to the precision
specification for the argument. If the precison is
missing, 6 digits are given; if the precision is
explicitly zero, no digits and no decimal point are
printed.
e The float or double arg is converted in the style
'[-]d.ddde+dd' where there is one digit before the
decimal point and the number after is equal to the
precision specification for the argument; when the
precision is missing, 6 digits are produced.
g The float or double arg is printed in style d, in
style f, or in style e, whichever gives full precision
in minimum space.
c The character arg is printed. NULL characters are
ignored.
s arg is taken to be a string (character pointer) and
characters from the string are printed until a NULL
character or until the number of characters indicated
by the precision specification is reached; however if
the precision is zero or missing all characters up to
a NULL are printed.
u The unsigned integer arg is converted to decimal and
printed (the result will be in the range zero to
65535).
% Print a '%'; no argument is converted.
In no case does a non-existent or small field width cause
truncation of a field; padding takes place only if the
specified field width exceeds the actual width. Characters
generated by printf are printed by putchar.
Examples:
To print a date and time in the form
Sunday, July 3, 10:02
where weekday and month are pointers to null-terminated
strings:
printf("%s, %s %d, %02d:%02d", weekday, month, day,
hour, min);
To print pi to 5 decimals:
printf("pi = %.5f", 4*atan(1.0));
SEE ALSO
putc, scanf
BUGS
Very wide fields (>MAXLINE characters) fail.
.pa
.heputc putc
Put Character or Word on a Stream
NAME
putc, putca, putchar, eputc
SYNOPSIS
#include <stdio.h>
int putc(c, stream)
int c;
FILE *stream;
int putca(c, stream)
int c;
FILE *stream;
int putchar(c)
int c;
int eputc(c)
char c;
DESCRIPTION
putc appends the character c to the named output stream. It
returns the character written. putca is the same as putc
except that '\n' is accompanied by '\r' when CROUTADD in
stdio.h is TRUE.
putchar(c) is defined as the macro putca(c, stdout),
returning c, in stdio.h.
eputc outputs c to the standard error device, stderr. eputc
is defined as the macro putca(c, stderr).
The standard stream stdout is normally buffered if and only
if the output does not refer to a terminal. The standard
stream stderr is by default unbuffered unconditionally (see
fopen). When an output stream is unbuffered information
appears on the destination file or terminal as soon as
written; when it is buffered, many characters are saved up
and written as a block. fflush (see fclose) may be used to
force the block out early.
putc updates the outrow[] and outcol[] of its stream->_unit.
SEE ALSO
fopen, fclose, getc, puts, printf, fread, stdio.h
DIAGNOSTICS
These functions return the constant EOF upon error.
.pa
.heputs puts
Put a String on a Stream
NAME
puts, fputs, eputs
SYNOPSIS
#include <stdio.h>
int puts(s)
STRING s;
int fputs(s, stream)
STRING s;
FILE *stream;
int eputs(s)
STRING s;
DESCRIPION
puts copies the text string s, followed by newline, to the
stdio device, and returns a newline character if successful,
EOF if not.
fputs copies the text string s to the named output stream.
It returns NULL if successful, EOF if not.
eputs puts the string out to the standard error device. It
returns newline if successful, EOL if not.
None of the routines copies the terminating NULL character.
SEE ALSO
fopen, gets, putc, printf, ferror, fwrite
BUGS
puts appends a newline, fputs does not, all in the name of
backward compatibility.
.pa
.herandom random
Random Number Generator Functions
NAME
randize, random, randnorm, randexp, urandom
SYNOPSIS
VOID randize(seed)
int seed;
double random()
double randnorm()
double randexp()
unsigned urandom()
DESCRIPTION
randize initializes the random number generator according to
seed. If seed is zero, an internal value is used to start
the generator; if a positive value is used, that value is
converted to a pseudorandom starting value; and if -1 is
used, an unknown value is used as the starter.
random returns a uniform random value in [0, 1].
randnorm returns a normally distributed random value with
zero mean and unit standard deviation.
randexp uses the function random() to return an
exponentially distributed random value characterized by unit
mean, i.e. -log(random()).
urandom returns a uniform random unsigned integer value in
[0, 65535].
Numbers generated have no serial correlation. Adjacent
samples of random and urandom numbers are uniformly
distributed over the 32-cube, and runs-up and runs-down
tests up to length 13 would require more than 1011 samples
to show deviation from theoretical. The period of the
generator is about 1.3 * 10154. The numbers form an
asymptotically random Tausworthe linear recurrance (modulo
2) sequence, described in Ref. 12, using the primitive
trinomial x521 + x32 + 1.
.pa
.heratfun ratfun
Rational Function Evaluation
NAME
ratfun
SYNOPSIS
double ratfun(x, P, Q, n, m)
double x, P[], Q[];
int n, m;
DESCRIPTION
ratfun returns the value of the rational function P(x)/Q(x)
where n = deg(P), m = deg(Q).
DIAGNOSTICS
If the denominator is zero, errno is set to ERANGE; then
positive INFINITY is returned if the numerator is non-
negative; otherwise, negative INFINITY is returned. On
underflow, errno is set to ERANGE, and zero is returned. On
overflow, errno is set to ERANGE and INFINITY of the proper
sign is returned.
.pa
.herkstep rkstep
Fourth Order Runga-Kutta
NAME
rkstep, rknstep
SYNOPSIS
VOID rkstep(f, h, t, yp)
double (*d)(), h, t, *yp;
VOID rknstep(N, f, h, t, y1, y2, dy, k, ys)
double (*f)(), h, t, y1[], y2[], dy[], k[], ys[];
DESCRIPTION
rkstep performs an integration step for a first-order diff
erential equation using the fourth order Runga-Kutta
formulas. The form of the equation is y' = f(t, y),
where y = *yp and differentication is with respect to the
first variable of f. (See Reference 3, pg. 896, formula
25.5.10)
rknstep performs an integration step for an N-tuple of
first-order ordinary differential equations using the fourth
order Runga-Kutta formulas referenced above. N is the
dimension of the tuple, y1 is the current vector state at
(time) t, y2 is the calculated N-tuple state value at (time)
t + h returned by rknstep, dy is a scratch array needed to
hold intermediate calculations accumulating the dy value, k
holds coefficients k1, k2, k3, and k4, and ys is for y
approximants for each equation. All of the scratch array
must have dimension not less than N.
The function f has 3 arguments; f(i, t, y), where i is the
vector component index, t is the differentication variable,
and y is the current state value vector. That is,
yi = f(i, t, y) for i = 1, 2,...,N. In both functions, h is
the step size.
.pa
.hescanf scanf
Formatted Input Conversion
NAME
scanf, fscanf, sscanf, unformat
SYNOPSIS
#include <stdio.h>
int scanf(format [ , pointer ] ... )
STRING format;
unsigned *pointer;
int fscanf(stream, format [ , pointer ] ... )
FILE *stream;
STRING format;
unsigned *pointer;
int sscanf(s, format [ , pointer ] ... )
STRING s, format;
int *pointer;
int unformat(get, format [ , pointer ] ... )
int (*get)();
STRING format;
int *pointer;
DESCRIPTION
scanf reads from the standard input stream stdin. fscanf
reads from the named input stream. sscanf reads from the
character string s. unformat utilizes the get function
argument to fetch characters. Each function reads
characters, interprets them according to format, and stores
the results in its remaining arguments. Each function
expects as arguments a control string format, described
below, and a set of pointer arguments indicating where the
converted input should be stored.
The control string usually contains conversion
specifications, which are used to direct interpretation of
input sequences. The control string may contain:
1. Blanks, tabs or newlines, which match optional white
space in the input.
2. An ordinary character (not %) which must match the
next character of the input stream.
3. Conversion specifications, consisting of the character
%, an optional assignment suppressing character *, an
optional numerical maximum field width, and a
conversion character.
A conversion specification directs the conversion of the
next input field; the result is placed in the variable
pointed to by the corresponding argument, unless assignment
suppression was indicated by *. An input field is defined
as a string of non-space characters; it extends to the next
inappropriate character or until the field width, if
specified, is exhausted.
The conversion character indicates the interpretation of the
input field; the corresponding pointer argument must usually
be of a restricted type. The following conversion
characters are legal:
% a single '%' is expected in the input at this point;
no assignment is done.
d a decimal integer is expected; the corresponding
argument should be an integer pointer.
o an octal integer is expected; the corresponding
argument should be an integer pointer.
x a hexadecimal integer is expected; the corresponding
argument should be an integer pointer.
s a character string is expected; the corresponding
argument should be a character pointer pointing to an
array of characters large enough to accept the string
and a terminating NULL, which will be added. The
input field is terminated by a space character or a
newline.
c a character is expected; the corresponding argument
should be a character pointer. The normal skip over
space characters is suppressed in this case; to read
the next non-space character, try '%1s'. If a field
width is given, the corresponding argument should
refer to a character array, and the indicated number
of characters is read.
e a floating point number is expected; the next field is
f converted accordingly and stored through the
corresponding argument, which should be a pointer to a
float. The input format for floating point numbers is
an optionally signed string of digits possibly
containing a decimal point, followed by an optional
exponent field consisting of an E or e followed by an
optionally signed integer.
[ indicates a string not to be delimited by space
characters. The left bracket is followed by a set of
characters and a right bracket; the characters between
the brackets define a set of characters making up the
string. If the first character is not circumflex (^),
or tilde (~), the input field is all characters until
the first character not in the set between the
brackets; if the first character after the left
bracket is ^ (or ~), the input field is all characters
until the first character which is in the remaining
set of characers between the brackets. The
corresponding argument must point to a character
array.
The conversion characters d, o and x may be capitalized or
preceeded by l to indicate that a pointer to long rather
than to int is in the argument list. Similarly, the
conversion characters e or f may be capitalized or preceded
by L to indicate a pointer to double rather than to float.
The conversion characters d, o and x may be preceeded by h
to indicate a pointer to short rather than to int. The
conversion hd may be shortened to only h to conform to
Kernighan and Ritchie (Reference 2).
The scanf functions return the number of successfully
matched and assigned input items. This can be used to
decide how many input items were found. The constant EOF is
returned upon end of input; note that this is different from
zero, which means that no conversion was done; if conversion
was intended, it was frustrated by an inappropriate
character in the input.
For example, the call
int i;
float x;
char name[50];
scanf( "%d%f%s", &i, &x, name);
with the input line
25 54.32E-1 synott
will assign to i the value 25, x the value 5.432, and name
will contain 'synott'. Or,
int i;
float x;
char name[50];
scanf("%2d%f%*d%[1234567890]", &i, &x, name);
with input
56789 0123 56a72
will assign 56 to i, 789.0 to x, skip '0123', and place the
string '56' in name. The next call to getchar will return
'a'.
The get argument of the unformat function itself uses a mode
argument: get(TRUE) is assumed to perform a character input,
and get(FALSE) does an unget on the last character fetched.
SEE ALSO
atof, getc, printf
DIAGNOSTICS
The scanf functions return EOF on end of input, and a short
count for missing or illegal data items.
BUGS
The success of incompatible types is not directly
determinable.
.pa
.hescreen i/o screen i/o
Screen Input/Output
NAME
altscrn, clrscrn, cursor, eraeol, eraeop, home, iniscrn,
normscrn, putscrn, uniscrn
SYNOPSIS
#include <scrnio.h>
BOOL altscrn()
VOID clrscrn()
BOOL cursor(r, c)
int r, c;
BOOL eraeol(r, c)
int r, c;
BOOL eraeop(r, c)
int r, c;
VOID home()
VOID iniscrn()
BOOL normscrn()
METACHAR putscrn(c)
int c;
VOID uniscrn()
DESCRIPTION
altscrn begins the alternate-intensity mode. If this is a
system supported function, altscrn returns TRUE; if not, it
returns FALSE.
clrscrn clears and erases the terminal screen and returns
the cursor to the home position.
cursor positions the cursor at row r, column c. If
successful, this function returns TRUE. If a coordinate
addreessing error is sensed, it will return FALSE.
eraeol erases row r from column c to the end of the line.
It will return TRUE if successful, or FALSE on improper r or
c. The cursor is positioned at row r, column c afterward.
eraeop erases from row r, column c to the end of the page.
TRUE is normally returned; improper r or c will cause
eraeop to return FALSE. The cursor is positioned at row r,
column c afterward.
home moves the cursor to row zero, column zero of the
terminal.
iniscrn sends the initialization sequence to the terminal,
if it exists.
normscrn begins the normal-intensity mode. It returns TRUE
if this function is supported, or FALSE if not.
putscrn sends the character c to the terminal in unbuffered
mode. outcol[STDOUT] and outrow[STDOUT] are correctly
updated, ie., putscrn will be ignored if the screen size has
been exceeded.
uniscrn sends the un-initialization sequence to the
terminal, if it exits.
Global variables outrow[STDOUT] and outcol[STDOUT] hold the
current position of the cursor at all times.
scrnio.h is the data file which declares all global data
necessary for the use of these terminal display functions.
scrnio.h should be included before stdio.h in every program
using screen i/o functions.
Row 0 is the topmost row, and column 0 is the leftmost
column.
BUGS
These functions may not operate on systems in which terminal
output cannot be direct.
.pa
.hesetbuf setbuf
Assign Buffer
NAME
setbuf
SYNOPSIS
VOID setbuf(fp, buffer)
FAST FILE *fp;
BUFFER buffer;
DESCRIPTION
setbuf is used after a stream has been opened but before it
is read or written. If fp already has a buffer assigned to
it, it causes the character array buffer to be used instead
of an automatically allocated buffer. Any data in the
existing buffer is lost. If buffer is the constant pointer
NULL, input/output will be completely unbuffered.
Use of setbuf(stdin, NULL) at the beginning of a program
assures that terminal input will be unbuffered.
BUGS
Unbuffered terminal input depends on whether
read(0, buffer, 1) returns a byte immediately or is
internally buffered for line editing purposes.
.pa
.hesgn sgn
Sign Function
NAME
sgn
SYNOPSIS
double sgn(x)
double x;
DESCRIPTION
sgn will return the double sgn function of x, i.e., +1, -1,
or 0, accordingly as x is positive, negative, or zero,
respectively.
SGN is the macro in header file defs.h which performs the
same function, except for side effects, and on all signed
numeric types.
.pa
.hesimpson simpson
Integration by Simpson's Modified Rule
NAME
simpson
SYNOPSIS
double simpson(func, lowlim, uplim, n)
double (*func)(), lowlim, uplim;
int n;
DESCRIPTION
simpson integrates the function func from lowlim to uplim
using 2n points, according to the Simpson integration rule.
The error value is given by
e = -(n * h5/90) * funciv(x)
where h = (uplim - lowlim)/(2n) and lowlim < x < uplim.
(see Reference 3, formula 25.4.6)
.pa
.hesin sin
Trigonometric Functions
NAME
sin, cos, tan, asin, acos, atan, atan2, cotan
SYNOPSIS
#include <mathcons.h>
double sin(x)
double x;
double cos(x)
double x;
double tan(x)
double x;
double asin(x)
double x;
double acos(x)
double x;
double atan(x)
double x;
double atan2(x, y)
double x, y;
double cotan(x)
double x;
DESCRIPTION
All of these functions were programmed using the algorithms
given in Software Manual for the Elementary Functions (see
Reference 5).
sin, cos and tan return trigonometric functions of radian
arguments. The magnitude of the argument should be checked
by the caller to make sure the result is meaningful. (see
Reference 5, pp. 125-149 and 150-173)
asin returns the arc sin in the range -pi/2 to +pi/2.
acos returns the arc cosine in the range zero to pi.
atan returns the arc tangent of x in the range -pi/2 to
+pi/2. (see Reference 5, pp. 194-216)
atan2 returns the arc tangent of x/y in the range -pi to +pi.
cotan returns the cotangent of x.
DIAGNOSTICS
Arguments of magnitude greater than unity cause asin and
acos to return value 0; errno is set to EDOM. The value of
tan at its singular points is INFINITY, and errno is set to
ERANGE.
BUGS
The value of tan for arguments greater than MAXANGLE is
garbage.
.pa
.hesinh sinh
Hyperbolic Functions
NAME
sinh, cosh, tanh
SYNOPSIS
#include <mathtyp.h>
double sinh(x)
double x;
double cosh(x)
double x;
double tanh(x)
double x;
DESCRIPTION
These functions compute the designated hyperbolic functions
for real arguments.
All were programmed using the algorithms given in Software
Manual for the Elementary Functions (see Reference 5, pp.
217-238 and 239-255).
DIAGNOSTICS
sinh and cosh return INFINITY of appropriate sign when the
correct value would overflow.
.pa
.hesortH sortH
Sort Functions
NAME
sortH, sortS, sortQ, sortB, qsort
SYNOPSIS
VOID sortH(n, comp, exch)
int n, (*comp)();
VOID (*exch)();
VOID sortS(n, comp, exch)
int n, (*comp)();
VOID (*exch)();
VOID sortQ(n, comp, exch)
int n, (*comp)();
VOID (*exch)();
VOID sortB(n, comp, exch)
int n, (*comp)();
VOID (*exch)();
VOID qsort(base, n, width, compar)
STRING base;
int n, width, (*compar)();
DESCRIPTION
Each of these functions will sort an array of size n with
respect to a comparison function comp(i, j), which is
positive, if and only if elements i and j of the array are
out of order. The exch(i, j) function exchanges the ith
and jth elements of the array. The name and type of array
are unknown to the sort routines, but must, of course, be
known to exch and comp.
sortH uses the heapsort algorithm, with time complexity
O(n * log(n)). (See Reference 10, pp. 87-92.)
sortS uses the Shell sort algorithm, with time complexity of
about O(n1.5). (See References 2 and 9.)
sortQ uses the quicksort algorithm, of time complexity
O(n * log(n)) to O(n2). (See Reference 11.)
sortB performs a bubble-sort in which large values bubble up
and low values shuttle down in the array, O(n) to O(n2).
qsort is another implementation of the quicksort algorithm.
The base is a pointer to the beginning of the data; n is the
number of elements; third is the width of an element in
bytes; last is the name of the comparison routine to be
called with two arguments, pointers to the elements being
compared. The comparison must return an integer greater
than zero if and only if the elements being compared are out
of sort.
.pa
.hetolower tolower
Conversion to Lower and Upper Case
NAME
tolower, toupper
SYNOPSIS
char tolower(c)
int c;
char toupper(c)
int c;
DESCRIPTION
tolower returns the lower case of c, if c is an upper-case
letter.
toupper returns the upper case of c, if c is a lower-case
letter.
TOLOWER and TOUPPER are the macros found in header file
ctype.h which are identical to the functions above, except
for side-effects.
.pa
.heungetc ungetc
Push Character Back into Input Stream
NAME
ungetc
SYNOPSIS
#include <stdio.h>
int ungetc(c, stream)
int c;
FILE *stream;
DESCRIPTION
ungetc pushes the character c back on an input stream. That
character will be returned by the next getc call on that
stream. ungetc returns c.
One character of pushback is guaranteed provided something
has been read from the stream and the stream is actually
buffered.
fseek erases all memory of pushed back characters.
SEE ALSO
getc, fseek
DIAGNOSTICS
ungetc returns EOF if c is EOF.
.he
.pa o
.PN 1
.FO 5-#
5. C U S T O M I Z A T I O N N O T E S
There are approximately 162 functions and 167 parameters
(constants, macros, and global variables) names in the portable C
subroutine library. Of these, 12 are system functions, for which
source code is not included, and another 145 functions and 152
parameters that are machine-independent. One of the system-level
functions and the remaining 5 functions and 56 parameters must be
customized to the ideosyncracies of the host environment. The
system interface functions are listed in Table 5-1, the elements
that must be given attention are listed in Table 5-2, and the
machine-independent elements are given in Table 5-3. All
elements are listed in Table 5-4.
The procedures for effecting the needed changes from the
distribution source is contained in the remainder of this
section.
.po11
Table 5-1: PORTABLE C LIBRARY SYSTEM INTERFACE
Element Type File Description
close function csys.lib Close file OS interface.
creat function csys.lib Create file function, OS interface.
exit function csys.lib Close all files and terminate program.
lseek function csys.lib Move file position using arg as offset.
open function csys.lib Open file for operation, OS interface.
read function csys.lib Read from stream into buffer: OS interfc
rename function csys.lib Rename a file: OS interface.
sbrk function csys.lib Set pointer to available memory: OS i/f.
unlink function csys.lib Unlink a file name from a file (delete).
write function csys.lib File write OS interface.
_exit function csys.lib Immediate termination of program.
.pa
Table 5-2: PORTABLE C LIBRARY COMPILER- & SYSTEM-DEPENDENT ELEMENTS
Element Type File Description
ALIGN typedef stdtyp.h K & R storage allocation header aligner.
ALTSCRN TEXT scrnio.h Terminal into alternate intensity string
astof function atof.c ASCII number to (double) float. Pointer.
BIG10X constant mathcons.h Largest 10^(2^(BIG10X -1)) < INFINITY
BIGX constant mathcons.h 16 * log2(INFINITY) - 1
BUFSIZ constant stdio.h I/O stream buffer size.
CB4L TBOOL scrnio.h Column-before-row boolean.
chrstc function chrstc.c Return int characteristic of double.
CLEARSCREEN TEXT scrnio.h Terminal clear-screen string.
COFFSET tiny scrnio.c Cursor lead-in column offset value.
CRINSUP constant stdio.h Set TRUE to suppress CR text input.
CROUTADD constant stdio.h Set true to echo '\n' with CR.
DPRECISION constant mathcons.h (int) PRECISION
EDOM constant errno.h Function argument not in defined domain.
EOF constant defs.h Standard End-of-File value.
ERAEOLN TEXT scrnio.c Terminal Erase-to-End-of-Line string.
ERAEOPG TEXT scrnio.h Terminal erase-to-end-of-page string.
fint function fint.c Float (double) INTeger-part function.
ftoa function ftoa.c Float (double) to ASCII conversion.
HEIGHT tiny scrnio.h Terminal height, number of lines.
HOME string scrnio.h Terminal cursor-to-home (0,0) string.
INFINITY constant mathcons.h Largest double value on this machine.
INFINLEG constant math.cons INFINITY / ROOTTWO.
ldexp function frexp.c Load exponent (multiply by power of 2).
LEADIN TEXT scrnio.h Cursor lead-in sequence.
LEAST constant mathcons.h Least double representable in machine.
LINDELETE TEXT scrnio.c Terminal line-delete string.
LININSERT TEXT scrnio.h Terminal line-delete string.
LOGINFINITY constant mathcons.h Largest argument of log function.
LOGLEAST constant mathcons.h Log of smallest machine number
mathcons.h header mathcons.h Constant file for math functions.
MAXCHANNELS constant global.h Maximum number of i/o channels at once.
MAXEXP constant mathcons.h Largest numeric characteristic.
MAXEXPG constant mathcons.h MAXEXP - 3 guard bits.
MAXLINE constant stdio.h Maximum no. of chars. on input line.
MAXSTREAM constant stdio.h Maximum number of buffered i/o streams.
MINEXP constant mathcons.h Characteristic of least machine double.
MINEXPG constant mathcons.h MINEXP + 3 guard bits.
NALLOC constant stdtyp.h No. of HEADER units for malloc().
NORMSCRN TEXT scrnio.h Terminal string, return normal intensity
PMODE constant stdio.h fopen() protection mode (for UNIX).
PRECISION constant mathcons.h -log10(WASHOUT).
RCENDER TEXT scrnio.h Row-column lead-in terminator.
RCSEPARATOR TEXT scrnio.h Cursor row, column separator string.
rename function csys.lib Rename a file: OS interface.
ROFFSET tiny scrnio.h Cursor lead-in row offset value.
RTHLFINF constant mathcons.h sqrt(INFINITY / 2).
SCRNINI TEXT scrnio.h Initialize-terminal string.
SCRNUNI TEXT scrnio.h Terminal un-initialize string.
SCRNWRAP TBOOL scrnio.h Signal for auto terminal wrap-around.
SMALLX constant mathcons.h 16 * log2(LEAST) + 1.0
PORTABLE C LIBRARY COMPILER- & SYSTEM-DEPENDENT ELEMENTS (cont.)
Element Type File Description
SYMLEAST constant mathcons.h Symmetric Least value (1/SYMLEAST) exist
SYS_EOF macro stdio.h System end-of-file marker, if any.
TANHXBIG constant mathcons (No. sig bits + 2) * log(2) / 2
TBITS typedef stdtyp.h Tiny (8 char min) for bit manipulation.
TBOOL typedef stdtyp.h Tiny (8 char min) used tor boolean.
TERMINAL TEXT scrnio.h Terminal identification string.
TINY macro stdtyp.h rvalue for tiny.
USELAST TBOOL scrnio.h Signal to use final terminal column.
UTINY macro stdtyp.h rvalue for utiny.
WASHOUT constant mathcons.h 1.0 + (x < WASHOUT) = 1.0 to precision.
WIDTH tiny scrnio.h Terminal width, number of characters.
XLT2ASCII TBOOL scrnio.h Translate-to-ASCII boolean.
.pa
Table 5-3: PORTABLE C LIBRARY SYSTEM-INDEPENDENT ELEMENTS
Element Type File Description
ABS macro defs.h Absolute value of any numeric type.
abs function abs.c Absolute value function, int.
acos function asin.c arc cosine, double.
allot function malloc.c malloc() without header overhead.
altscrn function scrnio.c Set terminal to alternate intensity.
AND macro defs.h Logical "and" operator, &&.
asin function asin.c Arc sine function, double.
astoi function atoi.c ASCII int to int. Also returns pointer.
astol function atol.c ASCII to long. Also returns pointer.
atan function atan.c Arc tangent, double.
atan2 function atan.c Two-argument arc tangent, double.
atof function atof.c ASCII to (double) float.
atoi function atoi.c ASCII to int.
atol function atol.c ASCII to long.
bitcount function bitcount.c K & R function counts bits in argument.
BITS typedef stdtyp.h Short used only for bit manipulation.
BOOL typedef stdtyp.h Int used only for boolean.
BUFFER typedef stdtyp.h Used only for pointers to char buffers.
calloc function malloc.c C allocation for arrays.
cbrt function cbrt.c Cube root function, double.
CBRTFOUR constant mathcons.h Cube root of 4.
CBRTTWO constant mathcons.h Cube root of 2.
ceil function floor.c Ceiling function of double.
clearerr macro stdio.h Reset error indicator on file stream.
clrscrn function scrnio.c Clear terminal screen.
cos function sin.c Cosine function, double.
cosh function cosh.c Hyperbolic cosine, double.
cotan function tan.c Cotangent function, double.
CURPOS constant stdio.h Current file position seek indicator.
cursor function scrnio.c Position terminal cursor at row, column.
eprintf function eprintf.c Formatted print to stderr.
eputc macro stdio.c Put character out to stderr.
eputs function eputs.c Put string out to stderr.
eraeol function scrnio.c Erase terminal screen to end of line.
eraeop function scrnio.c Erase terminal screen to end of page.
ERANGE constant errno.h Computed math value out of range.
erf function erf.c Error function, double.
erfc function erf.c Complimentary error function, double.
errno short global.h Standard error variable.
exp function exp.c Exponential function, double.
fabs function fabs.c Absolute value function, double.
FADEOUT constant mathcons.h Magnitude of washout term in Taylor ser.
FAIL constant defs.h Standard Failure value.
FALSE constant defs.h Standard False value.
fclosall function putc.c Close all buffered i/o streams.
fclose function fopen.c Close file using descriptor.
feof macro stdio.h Evaluate end-of-file status, int.
ferror macro stdio.h Boolean for file i/o error.
fflush function fopen.c Flush file buffers to the medium.
fgets function fgets.c Get string from file (buffered).
PORTABLE C LIBRARY SYSTEM-INDEPENDENT ELEMENTS (cont.)
Element Type File Description
FILE typedef stdio.h Standard file type declaration.
FILEND constant stdio.h File end seek position designator.
fileno macro stdio.h Return file descriptor of stream.
floor function floor.c Floor function, double.
flush function putc.c Flush output buffer when char overflow.
fmax function fminmax.c Maximum of a, b, double.
fmin function fminmax.c Minimum of a, b, double.
fopen function fopen.c Open file for buffered operation.
FOREVER macro defs.h Same as "for (::)".
format function format.c Basic output format utility.
FOURTHLOG2 constant mathcons.h log(2) / 4
fprintf function fprintf.c Formatted output to file.
fputs function fputs.c Put string out to file, unformatted.
frac function frac.c Fractional-part function, double.
fread function fread.c Buffered read from file.
free function malloc.c Free previously allocated storage.
frexp function frexp.c Fraction (mantissa) and exponent, double
fscanf function fscanf.c Formatted scan inputs from file.
fseek function fseek.c Buffered file reposition function.
ftell function ftell.c Return current file offset from origin.
fwrite function fwrite.c Buffered write to file.
getbuf function getbuf.c Get an i/o buffer from allot().
getc function getc.c Get character from file.
getca function getc.c Get ASCII char from buffered i/o stream.
getchar macro stdio.c Get character from stdin.
getf function getf.c Prompt and get double from stdin.
geti function geti.c Prompt and get integer from stdin.
getl function getl.c Prompt and get long from stdin.
getns function getns.c Prompt and get string from stdin.
gets function gets.c Get string from stdin.
GLOBAL macro stdtyp.h Pseudo storage class (extern) for port.
GZ macro defs.h Greater than Zero, GZ(x) = (x>0? x : 0)
HALFLOG2e constant mathcons.h log2(e) / 4
HEADER typedef stdtyp.h K & R storage allocation block type.
home function scrnio.c Home the terminal cursor.
hypot function hypot.c Compute hypotenuse of right triangle.
index function index.c Find position of char in string arg.
iniscrn function scrnio.c Initialize terminal screen output.
inverf function inverf.c Inverse of error function, erf, double.
inverfc function inverf.c Inverse of complementart error function.
INVPI constant mathcons.h 1.0 / pi
IObuffs buffers stdio.h I/O buffers for buffered streams.
IS macro defs.h Logical equivalence operator, ==.
isalnum function isalnum.c True if arg is alpha or number.
ISALNUM macro ctype.h True if arg is alpha or number.
isalpha function isalpha.c True if arg is alpha.
ISALPHA macro ctype.h True if arg is alpha.
isascii function isascii.c True if arg is < 128.
ISASCII macro ctype.h True if arg < 128.
iscntrl function iscntrl.c True if arg is control or DEL character.
PORTABLE C LIBRARY SYSTEM-INDEPENDENT ELEMENTS (cont.)
Element Type File Description
ISCNTRL macro ctype.h True if arg is control or DEL character.
isdigit function isdigit.c True if arg is decimal digit.
ISDIGIT macro ctype.h True if arg is decimal digit.
ishex function ishex.c Returns TRUE if argument is hex number.
islower function islower.c True if arg is lower-case alpha.
ISLOWER macro ctype.h True if arg is lower case alpha.
ISNT macro defs.h Logical non-equivalence operator, !=.
ISOCTAL macro ctype.h True if arg is octal character.
isoctal function isoctal.c Returns TRUE if argument is octal digit.
isok function isok.c Prompts and accepts y/n answer.
isprint function isprint.c True if arg is printable character.
ISPRINT macro ctype.h True if arg is printable character.
ispunct function ispunct.c True if arg is punctuation.
ISPUNCT macro ctype.h True if arg is not cntrl or alphanum.
isspace function isspace.c True if arg is space, tab, or newline.
ISSPACE macro ctype.h True if arg is space, tab, or newline.
isupper function isupper.c True if arg is upper-case alpha.
ISUPPER macro ctype True if arg is upper case alpha.
itoa function itoa.c Integer-to-Ascii conversion.
itoab function itoa.c Based int-ASCII conversion.
labs function labs.c Absolute value function, long.
LBITS typedef stdtyp.h Long used only for bit manipulation.
liberate function malloc.c free() without header overhead.
lmax function lminmax.c Maximum of a, b: long.
lmin function lminmax.c Minimum of a, b: long.
log function log.c Natural logarithm, double.
log10 function log10.c Common logarithm, double.
LOG10e constant mathcons.h Log of e base 10.
LOG10two constant mathcons.h log of 2 base 10.
log2 function log2.c Logarithm, base 2, double.
LOG2 constant mathcons.h Natural log of 2.
LOG2e constant mathcons.h Log of e base 2.
LOGe10 constant mathcons.h log of 10 base e.
ltoa function ltoa.c Long-to-ASCII conversion.
ltoab function ltoa.c Long to base conversion.
LURSHIFT macro defs.h Long Unsigned Right Shift long n, b bits
malloc function malloc.c Storage allocator: get memory from OS.
max function max.c Maximum of two integers.
MAX macro defs.h Maximum value of any two numbers.
MAXANGLE constant mathcons.h Maximum trigonometric angle, pi * 2^25.
METACHAR typedef stdtyp.h Augmented char to include EOF value.
min function min.c Minimum of two integer values.
MIN macro defs.h Minimum value of any two numeric values.
modf function modf.c Fraction and integer parts, double.
NO constant defs.h Standard NOt true value.
normscrn function scrnio.c Return terminal to normal intensity.
NOT macro defs.h Logical negation operator, !.
nprob function nprob.c Normal probability function.
nprobc function nprob.c Normal probability tail function, double
NULL constant defs.h Standard NULL pointer value.
PORTABLE C LIBRARY SYSTEM-INDEPENDENT ELEMENTS (cont.)
Element Type File Description
OR macro defs.h Logical inclusive-or operator, ||.
ORIGIN constant stdio.h Beginning of file seek designator.
outcol int array global.h Global variable, output column for chan.
outrow int array global.h Global variable, output row for channel.
PI constant mathcons.h pi
PIover2 constant mathcons.h pi / 2
PIover3 constant mathcons.h pi / 3
PIover4 constant mathcons.h pi / 4
PIover6 constant mathcons.h pi / 6
pow function pow.c Power: raise x to y power, double.
printf function printf.c Formatted print to stdout.
progname TEXT global.h Standard global string to hold prog name
putc function putc.c Buffered char output to stream.
putca function putc.c Buffered ASCII character output.
putchar macro stdio.h Put car out to stdout.
puts function puts.c Put string out to stdout.
putscrn function scrnio.c Put character directly to screen, unbuff
qsort function qsort.c Quicksort an array.
randexp function randexp.c Random number, double, exponential dist.
randize function random.c Seed the random number generator.
randnorm function randnorm.c Random number, double, normal distrib.
random function random.c Random number, double, uniform distrib.
ratfun function ratfun.c Rational function evaluation, double.
realloc function realloc.c Change storage allocator block size.
redirbuf function redirbuf.c Set redirected i/o buffer size.
rewind function rewind.c Rewind buffered i/o medium to beginning.
rindex function rindex.c Find last occurrence of char in string.
rknstep function rknstep.c 4-th order Runge-Kutta n-th order DE.
rkstep function rkstep.c 4-th order Runge-Kutta 1-st order DE.
ROOTHALF constant mathcons.h sqrt(0.5)
ROOTTWO constant mathcons.h sqrt(2.0)
round function round.c Round to nearest integer, double.
scanf function scanf.c Formatted scan input from stdin.
setbuf function setbuf.c Assign memory buffer to i/o stream.
SGN macro defs.h Sign value: +1, 0, -1, any numeric type.
sgn function sgn.c Sign function: +1, 0, -1, double.
simpson function simpson.c Integration by Simpson's modified rule.
sin function sin.c Sine function, double.
sinh function sinh.c Hyperbolic sine, double.
sortB function sortB.c Bubble-sort array in memory, in-place.
sortH function sortH.c Heapsort an array, in-place in memory.
sortQ function sortQ.c Quicksort memory array, in place.
sortS function sortS.c Shell-sort memory array, in-place.
sprintf function sprintf.c Formatted output to string buffer.
sqrt function sqrt.c Square-root function, double.
SQRT3 constant mathcons.h sqrt(3)
SQRT3m1 constant mathcons.h sqrt(3.0) - 1.0
sscanf function sscanf.c Formated scan input from string.
STDERR constant stdio.h Standard error output device number.
stderr macro stdio.h Standard buffered i/o error stream.
PORTABLE C LIBRARY SYSTEM-INDEPENDENT ELEMENTS (cont.)
Element Type File Description
STDIN constant stdio.h Standard input device number.
stdin macro stdio.h Standard buffered input stream.
STDOUT constant stdio.h Standard output device number.
stdout macro stdio.h Standard buffered output stream.
stradd function stradd.c Multiple string concatenation.
strcat function strcat.c Concatenate two strings.
strcmp function strcmp.c Compare two strings lexicographically.
strcpy function strcpy.c copy one string to another.
streql function streql.c Returns TRUE if strings are equal.
strindex function strindex.c Locate one string in another.
STRING typedef stdtyp.h Used only for pointers to strings.
strlen function strlen.c Compute length of string.
strncat function strncat Concatenate strings up to n chars.
strncmp function strncmp.c Compare strings up to n chars.
strncpy function strncpy.c Copy one string to another, up to n char
strsave function strsave.c Save (copy) a string to heap storage.
SUCCESS constant defs.h Standard non-FAIL value.
TABSTOP macro stdio.h Number of spaces per tab stop.
tan function tan.c Tangent function, double.
tanh function tanh.c Hyperbolic tangent, double.
TEXT typedef stdtyp.h Used only for ASCII printable characters
tiny typedef stdtyp.h A char used for signed int work.
tolower function tolower.c Convert arg to lower-case, if upper.
TOLOWER macro ctype.h Convert arg to lower-case, if upper.
toupper function toupper.c Convert to upper case, if lower.
TOUPPER macro ctype.h Convert arg to upper case, if lower.
TRUE constant defs.h Standard truth value.
TWOLOG2e constant mathcons.h 2 * log2(e)
TWOmSQRT3 constant mathcons.h 2 - sqrt(3)
TWOoverPI constant mathcons.h 2.0 / pi
unformat function unformat.c Basic scan function, arbitrary medium.
ungetc function ungetc.c Put char back into input stream.
uniscrn function scrnio.c Uninitialize terminal screen.
urandom function random.c Random number, unsigned, uniform distrib
URSHIFT macro defs.h Unsigned Right Shift, unsigned n, b bits
utiny typedef stdtyp.h A char used for unsigned int work.
utoa function utoa.c Unsigned to ASCII conversion.
VOID typedef stdtyp.h Used for function returning no value.
YES constant defs.h Standard truth value.
_ALLBUFF constant stdio.h Allocated buffer flag mask.
_BUSY constant stdio.h File open (busy) flag mask.
_EOF constant stdio.h Buffered stream end-of-file flag mask.
_IOERR constant stdio.h Buffered stream i/o error mask.
_RDONLY constant stdio.h File open signal to read only.
_RDWRIT constant stdio.h File open signal for read and write.
_WRONLY constant stdio.h File open signal for write-only access.
.pa
.po6
Table 5-4: PORTABLE C LIBRARY ELEMENTS
Element Type File Portable Description
ABS macro defs.h yes Absolute value of any numeric type.
abs function abs.c yes Absolute value function, int.
acos function asin.c yes arc cosine, double.
ALIGN typedef stdtyp.h customize K & R storage allocation header aligner.
allot function malloc.c yes malloc() without header overhead.
altscrn function scrnio.c yes Set terminal to alternate intensity.
ALTSCRN TEXT scrnio.h customize Terminal into alternate intensity string
AND macro defs.h yes Logical "and" operator, &&.
asin function asin.c yes Arc sine function, double.
astof function atof.c customize ASCII number to (double) float. Pointer.
astoi function atoi.c yes ASCII int to int. Also returns pointer.
astol function atol yes ASCII to long. Also returns pointer.
atan function atan.c yes Arc tangent, double.
atan2 function atan.c yes Two-argument arc tangent, double.
atof function atof.c yes ASCII to (double) float.
atoi function atoi.c yes ASCII to int.
atol function atol.c yes ASCII to long.
BIG10X constant mathcons.h customize Largest 10^(2^(BIG10X -1)) < INFINITY
BIGX constant mathcons.h customize 16 * log2(INFINITY) - 1
bitcount function bitcount.c yes K & R function counts bits in argument.
BITS typedef stdtyp.h yes Short used only for bit manipulation.
BOOL typedef stdtyp.h yes Int used only for boolean.
BUFFER typedef stdtyp.h yes Used only for pointers to char buffers.
BUFSIZ constant stdio.h customize I/O stream buffer size.
calloc function malloc.c yes C allocation for arrays.
CB4L TBOOL scrnio.h customize Column-before-row boolean.
cbrt function cbrt.c yes Cube root function, double.
CBRTFOUR constant mathcons.h yes Cube root of 4.
CBRTTWO constant mathcons.h yes Cube root of 2.
ceil function floor.c yes Ceiling function of double.
chrstc function chrstc.c customize Return int characteristic of double.
clearerr macro stdio.h yes Reset error indicator on file stream.
CLEARSCREEN TEXT scrnio.h customize Terminal clear-screen string.
close function csys.lib system Close file OS interface.
clrscrn function scrnio.c yes Clear terminal screen.
COFFSET tiny scrnio.c customize Cursor lead-in column offset value.
cos function sin.c yes Cosine function, double.
cosh function cosh.c yes Hyperbolic cosine, double.
cotan function tan.c yes Cotangent function, double.
creat function csys.lib system Create file function, OS interface.
CRINSUP constant stdio.h customize Set TRUE to suppress CR text input.
CROUTADD constant stdio.h customize Set true to echo '\n' with CR.
CURPOS constant stdio.h yes Current file position seek indicator.
cursor function scrnio.c yes Position terminal cursor at row, column.
DPRECISION constant mathcons.h customize (int) PRECISION
EDOM constant errno.h yes Function argument not in defined domain.
EOF constant defs.h yes Standard End-of-File value.
eprintf function eprintf.c yes Formatted print to stderr.
eputc macro stdio.c yes Put character out to stderr.
eputs function eputs.c yes Put string out to stderr.
eraeol function scrnio.c yes Erase terminal screen to end of line.
PORTABLE C LIBRARY ELEMENTS (cont.)
Element Type File Portable Description
ERAEOLN TEXT scrnio.c customize Terminal Erase-to-End-of-Line string.
eraeop function scrnio.c yes Erase terminal screen to end of page.
ERAEOPG TEXT scrnio.h customize Terminal erase-to-end-of-page string.
ERANGE constant errno.h yes Computed math value out of range.
erf function erf.c yes Error function, double.
erfc function erf.c yes Complimentary error function, double.
errno short global.h yes Standard error variable.
exit function csys.lib system Close all files and terminate program.
exp function exp.c yes Exponential function, double.
fabs function fabs.c yes Absolute value function, double.
FADEOUT constant mathcons.h yes Magnitude of washout term in Taylor ser.
FAIL constant defs.h yes Standard Failure value.
FALSE constant defs.h yes Standard False value.
FAST macro stdtyp.h customize Pseudo storage class (register).
fclosall function putc.c yes Close all buffered i/o streams.
fclose function fopen.c yes Close file using descriptor.
feof macro stdio.h yes Evaluate end-of-file status, int.
ferror macro stdio.h yes Boolean for file i/o error.
fflush function fopen.c yes Flush file buffers to the medium.
fgets function fgets.c yes Get string from file (buffered).
FILE typedef stdio.h yes Standard file type declaration.
FILEND constant stdio.h yes File end seek position designator.
fileno macro stdio.h yes Return file descriptor of stream.
fint function fint.c customize Float (double) INTeger-part function.
floor function floor.c yes Floor function, double.
flush function putc.c yes Flush output buffer when char overflow.
fmax function fminmax.c yes Maximum of a, b, double.
fmin function fminmax.c yes Minimum of a, b, double.
fopen function fopen.c yes Open file for buffered operation.
FOREVER macro defs.h yes Same as "for (::)".
format function format.c yes Basic output format utility.
FOURTHLOG2 constant mathcons.h yes log(2) / 4
fprintf function fprintf.c yes Formatted output to file.
fputs function fputs.c yes Put string out to file, unformatted.
frac function frac.c yes Fractional-part function, double.
fread function fread.c yes Buffered read from file.
free function malloc.c yes Free previously allocated storage.
frexp function frexp.c yes Fraction (mantissa) and exponent, double
fscanf function fscanf.c yes Formatted scan inputs from file.
fseek function fseek.c yes Buffered file reposition function.
ftell function ftell.c yes Return current file offset from origin.
ftoa function ftoa.c customize Float (double) to ASCII conversion.
fwrite function fwrite.c yes Buffered write to file.
getbuf function getbuf.c yes Get an i/o buffer from allot().
getc function getc.c yes Get character from file.
getca function getc.c yes Get ASCII char from buffered i/o stream.
getchar macro stdio.c yes Get character from stdin.
getf function getf.c yes Prompt and get double from stdin.
geti function geti.c yes Prompt and get integer from stdin.
getl function getl.c yes Prompt and get long from stdin.
PORTABLE C LIBRARY ELEMENTS (cont.)
Element Type File Portable Description
getns function getns.c yes Prompt and get string from stdin.
gets function gets.c yes Get string from stdin.
GLOBAL macro stdtyp.h yes Pseudo storage class (extern) for port.
GZ macro defs.h yes Greater than Zero, GZ(x) = (x>0? x : 0)
HALFLOG2e constant mathcons.h yes log2(e) / 4
HEADER typedef stdtyp.h yes K & R storage allocation block type.
HEIGHT tiny scrnio.h customize Terminal height, number of lines.
home function scrnio.c yes Home the terminal cursor.
HOME string scrnio.h customize Terminal cursor-to-home (0,0) string.
hypot function hypot.c yes Compute hypotenuse of right triangle.
index function index.c yes Find position of char in string arg.
INFINITY constant mathcons.h customize Largest double value on this machine.
INFINLEG constant math.cons customize INFINITY / ROOTTWO.
iniscrn function scrnio.c yes Initialize terminal screen output.
inverf function inverf.c yes Inverse of error function, erf, double.
inverfc function inverf.c yes Inverse of complementart error function.
INVPI constant mathcons.h yes 1.0 / pi
IObuffs buffers stdio.h yes I/O buffers for buffered streams.
IS macro defs.h yes Logical equivalence operator, ==.
isalnum function isalnum.c yes True if arg is alpha or number.
ISALNUM macro ctype.h yes True if arg is alpha or number.
isalpha function isalpha.c yes True if arg is alpha.
ISALPHA macro ctype.h yes True if arg is alpha.
isascii function isascii.c yes True if arg is < 128.
ISASCII macro ctype.h yes True if arg < 128.
iscntrl function iscntrl.c yes True if arg is control or DEL character.
ISCNTRL macro ctype.h yes True if arg is control or DEL character.
isdigit function isdigit.c yes True if arg is decimal digit.
ISDIGIT macro ctype.h yes True if arg is decimal digit.
ishex function ishex.c yes Returns TRUE if argument is hex number.
islower function islower.c yes True if arg is lower-case alpha.
ISLOWER macro ctype.h yes True if arg is lower case alpha.
ISNT macro defs.h yes Logical non-equivalence operator, !=.
ISOCTAL macro ctype.h yes True if arg is octal character.
isoctal function isoctal.c yes Returns TRUE if argument is octal digit.
isok function isok.c yes Prompts and accepts y/n answer.
isprint function isprint.c yes True if arg is printable character.
ISPRINT macro ctype.h yes True if arg is printable character.
ispunct function ispunct.c yes True if arg is punctuation.
ISPUNCT macro ctype.h yes True if arg is not cntrl or alphanum.
isspace function isspace.c yes True if arg is space, tab, or newline.
ISSPACE macro ctype.h yes True if arg is space, tab, or newline.
isupper function isupper.c yes True if arg is upper-case alpha.
ISUPPER macro ctype yes True if arg is upper case alpha.
itoa function itoa.c yes Integer-to-Ascii conversion.
itoab function itoa.c yes Based int-ASCII conversion.
labs function labs.c yes Absolute value function, long.
LBITS typedef stdtyp.h yes Long used only for bit manipulation.
ldexp function frexp.c customize Load exponent (multiply by power of 2).
LEADIN TEXT scrnio.h customize Cursor lead-in sequence.
PORTABLE C LIBRARY ELEMENTS (cont.)
Element Type File Portable Description
LEAST constant mathcons.h customize Least double representable in machine.
liberate function malloc.c yes free() without header overhead.
LINDELETE TEXT scrnio.c customize Terminal line-delete string.
LININSERT TEXT scrnio.h customize Terminal line-delete string.
lmax function lminmax.c yes Maximum of a, b: long.
lmin function lminmax.c yes Minimum of a, b: long.
LOCAL macro stdtyp.h customize Pseudo storage class (static) for port.
log function log.c yes Natural logarithm, double.
log10 function log10.c yes Common logarithm, double.
LOG10e constant mathcons.h yes Log of e base 10.
LOG10two constant mathcons.h yes log of 2 base 10.
log2 function log2.c yes Logarithm, base 2, double.
LOG2 constant mathcons.h yes Natural log of 2.
LOG2e constant mathcons.h yes Log of e base 2.
LOGe10 constant mathcons.h yes log of 10 base e.
LOGINFINITY constant mathcons.h customize Largest argument of log function.
LOGLEAST constant mathcons.h customize Log of smallest machine number
lseek function csys.lib system Move file position using arg as offset.
ltoa function ltoa.c yes Long-to-ASCII conversion.
ltoab function ltoa.c yes Long to base conversion.
LURSHIFT macro defs.h yes Long Unsigned Right Shift long n, b bits
malloc function malloc.c yes Storage allocator: get memory from OS.
max function max.c yes Maximum of two integers.
MAX macro defs.h yes Maximum value of any two numbers.
MAXANGLE constant mathcons.h yes Maximum trigonometric angle, pi * 2^25.
MAXCHANNELS constant global.h customize Maximum number of i/o channels at once.
MAXEXP constant mathcons.h customize Largest numeric characteristic.
MAXEXPG constant mathcons.h customize MAXEXP - 3 guard bits.
MAXLINE constant stdio.h customize Maximum no. of chars. on input line.
MAXSTREAM constant stdio.h customize Maximum number of buffered i/o streams.
METACHAR typedef stdtyp.h yes Augmented char to include EOF value.
min function min.c yes Minimum of two integer values.
MIN macro defs.h yes Minimum value of any two numeric values.
MINEXP constant mathcons.h customize Characteristic of least machine double.
MINEXPG constant mathcons.h customize MINEXP + 3 guard bits.
modf function modf.c yes Fraction and integer parts, double.
NALLOC constant stdtyp.h customize No. of HEADER units for malloc().
NO constant defs.h yes Standard NOt true value.
normscrn function scrnio.c yes Return terminal to normal intensity.
NORMSCRN TEXT scrnio.h customize Terminal string, return normal intensity
NOT macro defs.h yes Logical negation operator, !.
nprob function nprob.c yes Normal probability function.
nprobc function nprob.c yes Normal probability tail function, double
NULL constant defs.h yes Standard NULL pointer value.
open function csys.lib system Open file for operation, OS interface.
OR macro defs.h yes Logical inclusive-or operator, ||.
ORIGIN constant stdio.h yes Beginning of file seek designator.
outcol int array global.h yes Global variable, output column for chan.
outrow int array global.h yes Global variable, output row for channel.
PI constant mathcons.h yes pi
PORTABLE C LIBRARY ELEMENTS (cont.)
Element Type File Portable Description
PIover2 constant mathcons.h yes pi / 2
PIover3 constant mathcons.h yes pi / 3
PIover4 constant mathcons.h yes pi / 4
PIover6 constant mathcons.h yes pi / 6
PMODE constant stdio.h customize fopen() protection mode (for UNIX).
pow function pow.c yes Power: raise x to y power, double.
PRECISION constant mathcons.h customize -log10(WASHOUT).
printf function printf.c yes Formatted print to stdout.
progname TEXT global.h yes Standard global string to hold prog name
putc function putc.c yes Buffered char output to stream.
putca function putc.c yes Buffered ASCII character output.
putchar macro stdio.h yes Put car out to stdout.
puts function puts.c yes Put string out to stdout.
putscrn function scrnio.c yes Put character directly to screen, unbuff
qsort function qsort.c yes Quicksort an array.
randexp function randexp.c yes Random number, double, exponential dist.
randize function random.c yes Seed the random number generator.
randnorm function randnorm.c yes Random number, double, normal distrib.
random function random.c yes Random number, double, uniform distrib.
ratfun function ratfun.c yes Rational function evaluation, double.
RCENDER TEXT scrnio.h customize Row-column lead-in terminator.
RCSEPARATOR TEXT scrnio.h customize Cursor row, column separator string.
read function csys.lib system Read from stream into buffer: OS interfc
realloc function realloc.c yes Change storage allocator block size.
redirbuf function redirbuf.c yes Set redirected i/o buffer size.
rename function csys.lib customize Rename a file: OS interface.
rewind function rewind.c yes Rewind buffered i/o medium to beginning.
rindex function rindex.c yes Find last occurrence of char in string.
rknstep function rknstep.c yes 4-th order Runge-Kutta n-th order DE.
rkstep function rkstep.c yes 4-th order Runge-Kutta 1-st order DE.
ROFFSET tiny scrnio.h customize Cursor lead-in row offset value.
ROOTHALF constant mathcons.h yes sqrt(0.5)
ROOTTWO constant mathcons.h yes sqrt(2.0)
round function round.c yes Round to nearest integer, double.
RTHLFINF constant mathcons.h customize sqrt(INFINITY / 2).
sbrk function csys.lib system Set pointer to available memory: OS i/f.
scanf function scanf.c yes Formatted scan input from stdin.
SCRNINI TEXT scrnio.h customize Initialize-terminal string.
SCRNUNI TEXT scrnio.h customize Terminal un-initialize string.
SCRNWRAP TBOOL scrnio.h customize Signal for auto terminal wrap-around.
setbuf function setbuf.c yes Assign memory buffer to i/o stream.
SGN macro defs.h yes Sign value: +1, 0, -1, any numeric type.
sgn function sgn.c yes Sign function: +1, 0, -1, double.
simpson function simpson.c yes Integration by Simpson's modified rule.
sin function sin.c yes Sine function, double.
sinh function sinh.c yes Hyperbolic sine, double.
SMALLX constant mathcons.h customize 16 * log2(LEAST) + 1.0
sortB function sortB.c yes Bubble-sort array in memory, in-place.
sortH function sortH.c yes Heapsort an array, in-place in memory.
sortQ function sortQ.c yes Quicksort memory array, in place.
PORTABLE C LIBRARY ELEMENTS (cont.)
Element Type File Portable Description
sortS function sortS.c yes Shell-sort memory array, in-place.
sprintf function sprintf.c yes Formatted output to string buffer.
sqrt function sqrt.c yes Square-root function, double.
SQRT3 constant mathcons.h yes sqrt(3)
SQRT3m1 constant mathcons.h yes sqrt(3.0) - 1.0
sscanf function sscanf.c yes Formated scan input from string.
STDERR constant stdio.h yes Standard error output device number.
stderr macro stdio.h yes Standard buffered i/o error stream.
STDIN constant stdio.h yes Standard input device number.
stdin macro stdio.h yes Standard buffered input stream.
STDOUT constant stdio.h yes Standard output device number.
stdout macro stdio.h yes Standard buffered output stream.
stradd function stradd.c yes Multiple string concatenation.
strcat function strcat.c yes Concatenate two strings.
strcmp function strcmp.c yes Compare two strings lexicographically.
strcpy function strcpy.c yes copy one string to another.
streql function streql.c yes Returns TRUE if strings are equal.
strindex function strindex.c yes Locate one string in another.
STRING typedef stdtyp.h yes Used only for pointers to strings.
strlen function strlen.c yes Compute length of string.
strncat function strncat yes Concatenate strings up to n chars.
strncmp function strncmp.c yes Compare strings up to n chars.
strncpy function strncpy.c yes Copy one string to another, up to n char
strsave function strsave.c yes Save (copy) a string to heap storage.
SUCCESS constant defs.h yes Standard non-FAIL value.
SYMLEAST constant mathcons.h customize Symmetric Least value (1/SYMLEAST) exist
SYS_EOF macro stdio.h customize System end-of-file marker, if any.
TABSTOP macro stdio.h yes Number of spaces per tab stop.
tan function tan.c yes Tangent function, double.
tanh function tanh.c yes Hyperbolic tangent, double.
TANHXBIG constant mathcons customize (No. sig bits + 2) * log(2) / 2
TBITS typedef stdtyp.h customize Tiny (8 char min) for bit manipulation.
TBOOL typedef stdtyp.h customize Tiny (8 char min) used tor boolean.
TERMINAL TEXT scrnio.h customize Terminal identification string.
TEXT typedef stdtyp.h yes Used only for ASCII printable characters
tiny typedef stdtyp.h yes A char used for signed int work.
TINY macro stdtyp.h customize rvalue for tiny.
tolower function tolower.c yes Convert arg to lower-case, if upper.
TOLOWER macro ctype.h yes Convert arg to lower-case, if upper.
toupper function toupper.c yes Convert to upper case, if lower.
TOUPPER macro ctype.h yes Convert arg to upper case, if lower.
TRUE constant defs.h yes Standard truth value.
TWOLOG2e constant mathcons.h yes 2 * log2(e)
TWOmSQRT3 constant mathcons.h yes 2 - sqrt(3)
TWOoverPI constant mathcons.h yes 2.0 / pi
unformat function unformat.c yes Basic scan function, arbitrary medium.
ungetc function ungetc.c yes Put char back into input stream.
uniscrn function scrnio.c yes Uninitialize terminal screen.
unlink function csys.lib system Unlink a file name from a file (delete).
urandom function random.c yes Random number, unsigned, uniform distrib
PORTABLE C LIBRARY ELEMENTS (cont.)
Element Type File Portable Description
URSHIFT macro defs.h yes Unsigned Right Shift, unsigned n, b bits
USELAST TBOOL scrnio.h customize Signal to use final terminal column.
utiny typedef stdtyp.h yes A char used for unsigned int work.
UTINY macro stdtyp.h customize rvalue for utiny.
utoa function utoa.c yes Unsigned to ASCII conversion.
VOID typedef stdtyp.h yes Used for function returning no value.
WASHOUT constant mathcons.h customize 1.0 + (x < WASHOUT) = 1.0 to precision.
WIDTH tiny scrnio.h customize Terminal width, number of characters.
write function csys.lib system File write OS interface.
XLT2ASCII TBOOL scrnio.h customize Translate-to-ASCII boolean.
YES constant defs.h yes Standard truth value.
_ALLBUFF constant stdio.h yes Allocated buffer flag mask.
_BUSY constant stdio.h yes File open (busy) flag mask.
_EOF constant stdio.h yes Buffered stream end-of-file flag mask.
_exit function csys.lib system Immediate termination of program.
_IOERR constant stdio.h yes Buffered stream i/o error mask.
_RDONLY constant stdio.h yes File open signal to read only.
_RDWRIT constant stdio.h yes File open signal for read and write.
_WRONLY constant stdio.h yes File open signal for write-only access.
.po 17
Customization Procedure
To customize and install the C language portable subroutine
(function) library on a new host, the procedure is roughly as
follows:
1. Determine the extent to which the 10 system functions
given in Table 5-1 (i.e., all but rename) exist and
satisfy the interface specifications in Section 3 of
this manual. Determine the system run-time-support
interface requirements within the supplied library
file(s).
2. Program a rename function and convert it to relocatable
form suitable for the linking loader. Modify,
reprogram, or create any of the 10 system functions and
basic runtime-support functions to make them conform to
the interface, and similarly convert them to relocatable
form. If redirected i/o is handled within the
accessible system functions, alter these as appropriate
to call redirbuf to expand stdin or stdout stream
buffers to BUFSIZ; otherwise redirected i/o may be
considerably slower.
3. Extract the remaining (conformant) system functions in
Table 5-1 and all system run-time-support functions from
the existing host C function library, and insert all of
the system interface functions into a library or archive
file using the host library maintenance program, call it
csys.lib (or csys.a, etc., depending on host
restrictions). Observe topological sorting precedences
imposed by the system.
4. Customize the functions and parameters listed in Table
5-2, and recompile all functions in the portable C
library, using the host C compiler, into the form
expected by the linking loader. Combine these with
csys.lib functions, observing topological sort
precedences, into a new library file, call it lib0.lib
(or other, depending on host restrictions).
If the original host C library contains functions that
satisfy the functional descriptions herein given exactly, then
they may be extracted from this library and included into
lib0.lib in lieu of the portable-source version, if desired.
Customization Example
The procedure outlined in the preceding paragraphs is
perhaps best detailed by illustration. The following steps were
taken to install the portable C library functions into a file
acceptable for the AZTEC-II (Version 1.50, copyright Manx
Software Systems, Shrewsbury, NJ) C compiler on a microcomputer
with CP/M (a trademark of Digital Research, Inc., Pacific Grove,
CA) operating system. The C library file delivered with the
compiler was named libc.lib.
1. Study of existing system:
a. In extracting the system interface from libc.lib, it
was noted that _exit was absent, but all other system
functions were present.
b. The sbrk function (and an internally-used callcpm
function) did not function properly.
c. The STDIN read function always buffered characters
until a newline was received.
d. Redirected output was handled within the C system,
and if redirected to a file, was very slow, one written
character per disk access.
e. The C run-time system invoked strcpy, strcat,
strcmp, and strlen functions within the portable C
library being installed.
f. The system invoked a function closall_ to flush all
open streams and close all files, and a function putterr
to output a character to STDERR.
2. Corrective system actions:
a. rename was present and correct within the supplied
system, thus not reprogrammed.
b. The function puterr(c) was made, equivalent to
write(STDERR, &c, 1).
c. The _exit function was programmed as a direct jump
to the reboot function of the CP/M operating system.
d. A correctly functioning version of sbrk and callcpm
were available in source form on the vendor-supplied
diskettes; these were compiled and substituted for the
functions extracted from libc.lib.
e. A closeall_ function was programmed to call fclosall
(a function within putc); whenever buffered output
functions are used, output streams are thus properly
flushed and closed by exit. A dummy fclosall function
file was provided merely to close all open files in the
event output is unbuffered (putc not used).
f. Fortunately, the source code was available for read,
so it was modified to deliver single-character input
immediately, without waiting for a newline.
g. Since source code was available, it was possible to
alter the system croot function to call redirbuf when
input or output is redirected to a file. Note that both
getc and putc contain unreachable code to invoke
redirbuf; when STDIN or STDOUT is redirected to a file,
its stream buffer is thus expanded from 1 to BUFSIZ. A
file, dredir.c, containing a do-nothing dummy redirbuf
was supplied for loading when stdio.h streams are not
used.
3. Create system interface library.
All system functions were archived by the library manager
function into the C system interface library, csys.lib. The
contents and order of functions in the file are:
supp8080 fsubs puterr uexit callcpm croot
closall dfclose open read write lseek
blkio rename unlink block lsubs sbrk
dredir strlen strcpy strcmp strcat stradd
Note that it was necessary to include strlen and other string
functions in this file, because they were invoked within the
system functions (actually, croot).
4. Customize, compile, and form function library.
Constants, floating-point number formats, and other elements
to be customized were made to conform with the AZTEC-II compiler
specifications. See the following files for details:
atof.c chrstc.c defs.h errno.h fint.c frexp.c
ftoa.c global.h mathcons.h scrnio.h stdio.h
stdtyp.h
All non-math library functions were compiled and collected
into the file lib0.lib in the following order:
random getf geti getl isok getns
sortB sortH sortS bitcount scrnio printf
eprintf fprintf sprintf fscanf format eputs
sscanf scanf fwrite unformat fputs ftoa
fgets puts putc fopen rewind qsort
fseek fread gets getc redirbuf getbuf
atof strsave realloc sortq atoi setbuf
isupper islower ispunct isoctal ishex isprint
iscntrl isascii isalnum atol malloc rindex
min max lminmax labs itoa ftell
ungetc index ltoa isdigit isspace isalpha
abs utoa tolower toupper strncmp strncal
strindex streql strncpy
A separate library file, mathlib, was made to contain the
mathematical functions:
asin randnorm randexp hypot cosh cbrt
sqrt tanh tan sinh sin nprob
inverf erf rkstep rknstep pow floor
exp log2 log10 log frexp sgn
ratfun fminmax modf chrstc round frac
fint fabs atan simpson
Due to the fact that the vendor linkage editor was incapable
of working with files larger that 64K, it was necessary to leave
the library in these three segments.
.pa o
.heappendix appendix
.PN 1
.FO A-#
A. R E F E R E N C E S
1. UNIX Programmer's Manual, Bell Telephone Laboratories, Inc.,
Murray Hill, New Jersey, 1983.
2. Kernighan, Brian W., and Ritchie, Dennis M., The C
Programming Language, Prentice-Hall, Inc., Englewood Cliffs,
New Jersey, 1978.
3. Handbook of Mathematical Functions, National Bureau of
Standards Applied Mathematics Series #55, U.S. Government
Printing Office, Washington, D.C., 1964.
4. Plum, Thomas, C Programming Standards and Guidelines,
Version U (UNIX and offspring), Plum Hall, Inc., Cardiff,
New Jersey, 1982.
5. Coty, William J., Jr., and Waite, William, Software Manual
for the Elementary Functions, Prentice-Hall Series in
Computational Mathematics, Prentice-Hall, Inc., Inglewood
Cliffs, New Jersey, 1980.
6. J. F. Hart, E. W. Cheney, C. L. Lawson, H. J. Maehly, C. K.
Mesztenyi, J. R. Rice, H. C. Thacher, Jr., and C. Witzgall,
Computer Approximations, John Wiley & Sons, Inc., New York,
New York, 1968.
7. Schonfelder, J. L., Mathematics of Computation, Volume 32,
No. 144, October, 1978, pp. 1232-1240.
8. Blair, J. M., et. al., "Rational Chebyshev Approximations
for the Inverse Error Function", Mathematics of Computation,
Volume 30, No. 136, October, 1976.
9. Wirth, Nicklaus, Algorithms + Data Structures = Programs,
Prentice-Hall, Inc., Englewood Cliffs, New Jersey, 1976.
10. Aho, Alfred v., Hopcroft, John E., and Ullman, Jeffrey D.,
The Design and Analysis of Computer Algorithms, Addison-
Wesley Publishing Company, Reading, Massachusetts, 1975, pp.
87-92.
11. Knuth, Donald E., Art of Computer Programming, Vol. 2,
Semi-Numerical Algorithms, Addison-Wesley Publishing
Company, Reading, Massachusetts, 1973.
12. Tausworthe, R. C., "Random numbers generated by linear
recurrence modulo two", Mathematics of Computation, Volume
19, 1965, pp. 201-209.
13. Purdom, Jack, The C Programmer's Library, Que Corp.,
Indianapolis, 1984.
14. The C User's Group Newsletters, McPhereson, K. S., Vol. I,
No. 1, June, 1981, through Vol. II, No. 6, March, 1985.
15. Portable C Subroutine Library, Vol. II, Jet Propulsion
Laboratory, 1985.
.pa o
.PN 1
.FO B-#
B. I N D E X
.FI B:USEGUIDE.IDX